blob: 68618bc3371ed3e7cff99c03b6b3526a42e3f92c [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.
621 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
622 std::vector<DWARFDebugLine::Row> &Rows,
623 unsigned AdddressSize);
624
625 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000626
627 /// \brief Emit the .debug_pubnames contribution for \p Unit.
628 void emitPubNamesForUnit(const CompileUnit &Unit);
629
630 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
631 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000632
633 /// \brief Emit a CIE.
634 void emitCIE(StringRef CIEBytes);
635
636 /// \brief Emit an FDE with data \p Bytes.
637 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
638 StringRef Bytes);
639
640 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000641};
642
643bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
644 std::string ErrorStr;
645 std::string TripleName;
646 StringRef Context = "dwarf streamer init";
647
648 // Get the target.
649 const Target *TheTarget =
650 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
651 if (!TheTarget)
652 return error(ErrorStr, Context);
653 TripleName = TheTriple.getTriple();
654
655 // Create all the MC Objects.
656 MRI.reset(TheTarget->createMCRegInfo(TripleName));
657 if (!MRI)
658 return error(Twine("no register info for target ") + TripleName, Context);
659
660 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
661 if (!MAI)
662 return error("no asm info for target " + TripleName, Context);
663
664 MOFI.reset(new MCObjectFileInfo);
665 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000666 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
Frederic Rissc99ea202015-02-28 00:29:11 +0000667 *MC);
668
669 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
670 if (!MAB)
671 return error("no asm backend for target " + TripleName, Context);
672
673 MII.reset(TheTarget->createMCInstrInfo());
674 if (!MII)
675 return error("no instr info info for target " + TripleName, Context);
676
677 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
678 if (!MSTI)
679 return error("no subtarget info for target " + TripleName, Context);
680
Eric Christopher0169e422015-03-10 22:03:14 +0000681 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000682 if (!MCE)
683 return error("no code emitter for target " + TripleName, Context);
684
685 // Create the output file.
686 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000687 OutFile =
688 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000689 if (EC)
690 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
691
Rafael Espindolaf696df12015-03-16 22:29:29 +0000692 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000693 *MSTI, false,
694 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000695 if (!MS)
696 return error("no object streamer for target " + TripleName, Context);
697
698 // Finally create the AsmPrinter we'll use to emit the DIEs.
699 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
700 if (!TM)
701 return error("no target machine for target " + TripleName, Context);
702
703 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
704 if (!Asm)
705 return error("no asm printer for target " + TripleName, Context);
706
Frederic Riss25440872015-03-13 23:30:31 +0000707 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000708 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000709 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000710 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000711
Frederic Rissc99ea202015-02-28 00:29:11 +0000712 return true;
713}
714
715bool DwarfStreamer::finish() {
716 MS->Finish();
717 return true;
718}
719
Frederic Rissb8b43d52015-03-04 22:07:44 +0000720/// \brief Set the current output section to debug_info and change
721/// the MC Dwarf version to \p DwarfVersion.
722void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
723 MS->SwitchSection(MOFI->getDwarfInfoSection());
724 MC->setDwarfVersion(DwarfVersion);
725}
726
727/// \brief Emit the compilation unit header for \p Unit in the
728/// debug_info section.
729///
730/// A Dwarf scetion header is encoded as:
731/// uint32_t Unit length (omiting this field)
732/// uint16_t Version
733/// uint32_t Abbreviation table offset
734/// uint8_t Address size
735///
736/// Leading to a total of 11 bytes.
737void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
738 unsigned Version = Unit.getOrigUnit().getVersion();
739 switchToDebugInfoSection(Version);
740
741 // Emit size of content not including length itself. The size has
742 // already been computed in CompileUnit::computeOffsets(). Substract
743 // 4 to that size to account for the length field.
744 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
745 Asm->EmitInt16(Version);
746 // We share one abbreviations table across all units so it's always at the
747 // start of the section.
748 Asm->EmitInt32(0);
749 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
750}
751
752/// \brief Emit the \p Abbrevs array as the shared abbreviation table
753/// for the linked Dwarf file.
754void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
755 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
756 Asm->emitDwarfAbbrevs(Abbrevs);
757}
758
759/// \brief Recursively emit the DIE tree rooted at \p Die.
760void DwarfStreamer::emitDIE(DIE &Die) {
761 MS->SwitchSection(MOFI->getDwarfInfoSection());
762 Asm->emitDwarfDIE(Die);
763}
764
Frederic Rissef648462015-03-06 17:56:30 +0000765/// \brief Emit the debug_str section stored in \p Pool.
766void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000767 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000768 for (auto *Entry = Pool.getFirstEntry(); Entry;
769 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000770 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000771 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
772}
773
Frederic Riss25440872015-03-13 23:30:31 +0000774/// \brief Emit the debug_range section contents for \p FuncRange by
775/// translating the original \p Entries. The debug_range section
776/// format is totally trivial, consisting just of pairs of address
777/// sized addresses describing the ranges.
778void DwarfStreamer::emitRangesEntries(
779 int64_t UnitPcOffset, uint64_t OrigLowPc,
780 FunctionIntervals::const_iterator FuncRange,
781 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
782 unsigned AddressSize) {
783 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
784
785 // Offset each range by the right amount.
786 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
787 for (const auto &Range : Entries) {
788 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
789 warn("unsupported base address selection operation",
790 "emitting debug_ranges");
791 break;
792 }
793 // Do not emit empty ranges.
794 if (Range.StartAddress == Range.EndAddress)
795 continue;
796
797 // All range entries should lie in the function range.
798 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
799 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
800 warn("inconsistent range data.", "emitting debug_ranges");
801 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
802 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
803 RangesSectionSize += 2 * AddressSize;
804 }
805
806 // Add the terminator entry.
807 MS->EmitIntValue(0, AddressSize);
808 MS->EmitIntValue(0, AddressSize);
809 RangesSectionSize += 2 * AddressSize;
810}
811
Frederic Riss563b1b02015-03-14 03:46:51 +0000812/// \brief Emit the debug_aranges contribution of a unit and
813/// if \p DoDebugRanges is true the debug_range contents for a
814/// compile_unit level DW_AT_ranges attribute (Which are basically the
815/// same thing with a different base address).
816/// Just aggregate all the ranges gathered inside that unit.
817void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
818 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000819 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
820 // Gather the ranges in a vector, so that we can simplify them. The
821 // IntervalMap will have coalesced the non-linked ranges, but here
822 // we want to coalesce the linked addresses.
823 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
824 const auto &FunctionRanges = Unit.getFunctionRanges();
825 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
826 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000827 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
828 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000829
830 // The object addresses where sorted, but again, the linked
831 // addresses might end up in a different order.
832 std::sort(Ranges.begin(), Ranges.end());
833
Frederic Riss563b1b02015-03-14 03:46:51 +0000834 if (!Ranges.empty()) {
835 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
836
Rafael Espindola9ab09232015-03-17 20:07:06 +0000837 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
838 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000839
840 unsigned HeaderSize =
841 sizeof(int32_t) + // Size of contents (w/o this field
842 sizeof(int16_t) + // DWARF ARange version number
843 sizeof(int32_t) + // Offset of CU in the .debug_info section
844 sizeof(int8_t) + // Pointer Size (in bytes)
845 sizeof(int8_t); // Segment Size (in bytes)
846
847 unsigned TupleSize = AddressSize * 2;
848 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
849
850 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000851 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000852 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
853 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
854 Asm->EmitInt8(AddressSize); // Address size
855 Asm->EmitInt8(0); // Segment size
856
Lang Hames9ff69c82015-04-24 19:11:51 +0000857 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000858
859 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
860 ++Range) {
861 uint64_t RangeStart = Range->first;
862 MS->EmitIntValue(RangeStart, AddressSize);
863 while ((Range + 1) != End && Range->second == (Range + 1)->first)
864 ++Range;
865 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
866 }
867
868 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000869 Asm->OutStreamer->EmitIntValue(0, AddressSize);
870 Asm->OutStreamer->EmitIntValue(0, AddressSize);
871 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000872 }
873
874 if (!DoDebugRanges)
875 return;
876
877 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
878 // Offset each range by the right amount.
879 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000880 // Emit coalesced ranges.
881 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000882 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000883 while (Range + 1 != End && Range->second == (Range + 1)->first)
884 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000885 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000886 RangesSectionSize += 2 * AddressSize;
887 }
888
889 // Add the terminator entry.
890 MS->EmitIntValue(0, AddressSize);
891 MS->EmitIntValue(0, AddressSize);
892 RangesSectionSize += 2 * AddressSize;
893}
894
Frederic Rissdfb97902015-03-14 15:49:07 +0000895/// \brief Emit location lists for \p Unit and update attribtues to
896/// point to the new entries.
897void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
898 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000899 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000900
901 if (Attributes.empty())
902 return;
903
904 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
905
906 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
907 const DWARFSection &InputSec = Dwarf.getLocSection();
908 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
909 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000910 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000911 int64_t UnitPcOffset = 0;
912 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
913 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
914 if (OrigLowPc != -1ULL)
915 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
916
917 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000918 uint32_t Offset = Attr.first.get();
919 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000920 // This is the quantity to add to the old location address to get
921 // the correct address for the new one.
922 int64_t LocPcOffset = Attr.second + UnitPcOffset;
923 while (Data.isValidOffset(Offset)) {
924 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
925 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
926 LocSectionSize += 2 * AddressSize;
927 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000928 Asm->OutStreamer->EmitIntValue(0, AddressSize);
929 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000930 break;
931 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000932 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
933 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000934 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000935 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000936 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000937 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000938 StringRef(InputSec.Data.substr(Offset, Length)));
939 Offset += Length;
940 LocSectionSize += Length + 2;
941 }
942 }
943}
944
Frederic Riss63786b02015-03-15 20:45:43 +0000945void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
946 unsigned MinInstLength,
947 std::vector<DWARFDebugLine::Row> &Rows,
948 unsigned PointerSize) {
949 // Switch to the section where the table will be emitted into.
950 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000951 MCSymbol *LineStartSym = MC->createTempSymbol();
952 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000953
954 // The first 4 bytes is the total length of the information for this
955 // compilation unit (not including these 4 bytes for the length).
956 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000957 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000958 // Copy Prologue.
959 MS->EmitBytes(PrologueBytes);
960 LineSectionSize += PrologueBytes.size() + 4;
961
Frederic Rissc3820d02015-03-15 22:20:28 +0000962 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000963 raw_svector_ostream EncodingOS(EncodingBuffer);
964
965 if (Rows.empty()) {
966 // We only have the dummy entry, dsymutil emits an entry with a 0
967 // address in that case.
968 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
969 MS->EmitBytes(EncodingOS.str());
970 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000971 MS->EmitLabel(LineEndSym);
972 return;
973 }
974
975 // Line table state machine fields
976 unsigned FileNum = 1;
977 unsigned LastLine = 1;
978 unsigned Column = 0;
979 unsigned IsStatement = 1;
980 unsigned Isa = 0;
981 uint64_t Address = -1ULL;
982
983 unsigned RowsSinceLastSequence = 0;
984
985 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
986 auto &Row = Rows[Idx];
987
988 int64_t AddressDelta;
989 if (Address == -1ULL) {
990 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
991 MS->EmitULEB128IntValue(PointerSize + 1);
992 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
993 MS->EmitIntValue(Row.Address, PointerSize);
994 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
995 AddressDelta = 0;
996 } else {
997 AddressDelta = (Row.Address - Address) / MinInstLength;
998 }
999
1000 // FIXME: code copied and transfromed from
1001 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
1002 // this code, but the current compatibility requirement with
1003 // classic dsymutil makes it hard. Revisit that once this
1004 // requirement is dropped.
1005
1006 if (FileNum != Row.File) {
1007 FileNum = Row.File;
1008 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
1009 MS->EmitULEB128IntValue(FileNum);
1010 LineSectionSize += 1 + getULEB128Size(FileNum);
1011 }
1012 if (Column != Row.Column) {
1013 Column = Row.Column;
1014 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
1015 MS->EmitULEB128IntValue(Column);
1016 LineSectionSize += 1 + getULEB128Size(Column);
1017 }
1018
1019 // FIXME: We should handle the discriminator here, but dsymutil
1020 // doesn' consider it, thus ignore it for now.
1021
1022 if (Isa != Row.Isa) {
1023 Isa = Row.Isa;
1024 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
1025 MS->EmitULEB128IntValue(Isa);
1026 LineSectionSize += 1 + getULEB128Size(Isa);
1027 }
1028 if (IsStatement != Row.IsStmt) {
1029 IsStatement = Row.IsStmt;
1030 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
1031 LineSectionSize += 1;
1032 }
1033 if (Row.BasicBlock) {
1034 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
1035 LineSectionSize += 1;
1036 }
1037
1038 if (Row.PrologueEnd) {
1039 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
1040 LineSectionSize += 1;
1041 }
1042
1043 if (Row.EpilogueBegin) {
1044 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
1045 LineSectionSize += 1;
1046 }
1047
1048 int64_t LineDelta = int64_t(Row.Line) - LastLine;
1049 if (!Row.EndSequence) {
1050 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
1051 MS->EmitBytes(EncodingOS.str());
1052 LineSectionSize += EncodingBuffer.size();
1053 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +00001054 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +00001055 Address = Row.Address;
1056 LastLine = Row.Line;
1057 RowsSinceLastSequence++;
1058 } else {
1059 if (LineDelta) {
1060 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
1061 MS->EmitSLEB128IntValue(LineDelta);
1062 LineSectionSize += 1 + getSLEB128Size(LineDelta);
1063 }
1064 if (AddressDelta) {
1065 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
1066 MS->EmitULEB128IntValue(AddressDelta);
1067 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1068 }
1069 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
1070 MS->EmitBytes(EncodingOS.str());
1071 LineSectionSize += EncodingBuffer.size();
1072 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +00001073 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +00001074 Address = -1ULL;
1075 LastLine = FileNum = IsStatement = 1;
1076 RowsSinceLastSequence = Column = Isa = 0;
1077 }
1078 }
1079
1080 if (RowsSinceLastSequence) {
1081 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
1082 MS->EmitBytes(EncodingOS.str());
1083 LineSectionSize += EncodingBuffer.size();
1084 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +00001085 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +00001086 }
1087
1088 MS->EmitLabel(LineEndSym);
1089}
1090
Frederic Rissbce93ff2015-03-16 02:05:10 +00001091/// \brief Emit the pubnames or pubtypes section contribution for \p
1092/// Unit into \p Sec. The data is provided in \p Names.
1093void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001094 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001095 const std::vector<CompileUnit::AccelInfo> &Names) {
1096 if (Names.empty())
1097 return;
1098
1099 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001100 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001101 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1102 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001103
1104 bool HeaderEmitted = false;
1105 // Emit the pubnames for this compilation unit.
1106 for (const auto &Name : Names) {
1107 if (Name.SkipPubSection)
1108 continue;
1109
1110 if (!HeaderEmitted) {
1111 // Emit the header.
1112 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001113 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001114 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001115 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001116 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1117 HeaderEmitted = true;
1118 }
1119 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001120 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001121 StringRef(Name.Name.data(), Name.Name.size() + 1));
1122 }
1123
1124 if (!HeaderEmitted)
1125 return;
1126 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001127 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001128}
1129
1130/// \brief Emit .debug_pubnames for \p Unit.
1131void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1132 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1133 "names", Unit, Unit.getPubnames());
1134}
1135
1136/// \brief Emit .debug_pubtypes for \p Unit.
1137void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1138 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1139 "types", Unit, Unit.getPubtypes());
1140}
1141
Frederic Riss5a642072015-06-05 23:06:11 +00001142/// \brief Emit a CIE into the debug_frame section.
1143void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1144 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1145
1146 MS->EmitBytes(CIEBytes);
1147 FrameSectionSize += CIEBytes.size();
1148}
1149
1150/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1151/// contains the FDE data without the length, CIE offset and address
1152/// which will be replaced with the paramter values.
1153void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1154 uint32_t Address, StringRef FDEBytes) {
1155 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1156
1157 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1158 MS->EmitIntValue(CIEOffset, 4);
1159 MS->EmitIntValue(Address, AddrSize);
1160 MS->EmitBytes(FDEBytes);
1161 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1162}
1163
Frederic Rissd3455182015-01-28 18:27:01 +00001164/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001165///
1166/// The link of the dwarf information from the object files will be
1167/// driven by the selection of 'root DIEs', which are DIEs that
1168/// describe variables or functions that are present in the linked
1169/// binary (and thus have entries in the debug map). All the debug
1170/// information that will be linked (the DIEs, but also the line
1171/// tables, ranges, ...) is derived from that set of root DIEs.
1172///
1173/// The root DIEs are identified because they contain relocations that
1174/// correspond to a debug map entry at specific places (the low_pc for
1175/// a function, the location for a variable). These relocations are
1176/// called ValidRelocs in the DwarfLinker and are gathered as a very
1177/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001178class DwarfLinker {
1179public:
Frederic Rissb9818322015-02-28 00:29:07 +00001180 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1181 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001182 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001183
Frederic Rissb8b43d52015-03-04 22:07:44 +00001184 ~DwarfLinker() {
1185 for (auto *Abbrev : Abbreviations)
1186 delete Abbrev;
1187 }
1188
Frederic Rissd3455182015-01-28 18:27:01 +00001189 /// \brief Link the contents of the DebugMap.
1190 bool link(const DebugMap &);
1191
1192private:
Frederic Riss563cba62015-01-28 22:15:14 +00001193 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001194 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001195
1196 /// \brief Called at the end of a debug object link.
1197 void endDebugObject();
1198
Frederic Riss1036e642015-02-13 23:18:22 +00001199 /// \defgroup FindValidRelocations Translate debug map into a list
1200 /// of relevant relocations
1201 ///
1202 /// @{
1203 struct ValidReloc {
1204 uint32_t Offset;
1205 uint32_t Size;
1206 uint64_t Addend;
1207 const DebugMapObject::DebugMapEntry *Mapping;
1208
1209 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1210 const DebugMapObject::DebugMapEntry *Mapping)
1211 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1212
1213 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1214 };
1215
1216 /// \brief The valid relocations for the current DebugMapObject.
1217 /// This vector is sorted by relocation offset.
1218 std::vector<ValidReloc> ValidRelocs;
1219
1220 /// \brief Index into ValidRelocs of the next relocation to
1221 /// consider. As we walk the DIEs in acsending file offset and as
1222 /// ValidRelocs is sorted by file offset, keeping this index
1223 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001224 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001225 unsigned NextValidReloc;
1226
1227 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1228 const DebugMapObject &DMO);
1229
1230 bool findValidRelocs(const object::SectionRef &Section,
1231 const object::ObjectFile &Obj,
1232 const DebugMapObject &DMO);
1233
1234 void findValidRelocsMachO(const object::SectionRef &Section,
1235 const object::MachOObjectFile &Obj,
1236 const DebugMapObject &DMO);
1237 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001238
Frederic Riss84c09a52015-02-13 23:18:34 +00001239 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1240 ///
1241 /// @{
1242 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1243 /// keep. Store that information in \p CU's DIEInfo.
1244 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1245 const DebugMapObject &DMO, CompileUnit &CU,
1246 unsigned Flags);
1247
1248 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1249 enum TravesalFlags {
1250 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1251 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1252 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1253 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001254 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss84c09a52015-02-13 23:18:34 +00001255 };
1256
1257 /// \brief Mark the passed DIE as well as all the ones it depends on
1258 /// as kept.
1259 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1260 CompileUnit::DIEInfo &MyInfo,
1261 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001262 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001263
1264 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1265 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1266 unsigned Flags);
1267
1268 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1269 CompileUnit &Unit,
1270 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1271
1272 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1273 CompileUnit &Unit,
1274 CompileUnit::DIEInfo &MyInfo,
1275 unsigned Flags);
1276
1277 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1278 CompileUnit::DIEInfo &Info);
1279 /// @}
1280
Frederic Rissb8b43d52015-03-04 22:07:44 +00001281 /// \defgroup Linking Methods used to link the debug information
1282 ///
1283 /// @{
1284 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1285 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1286 /// stripped out and addresses have been rewritten according to the
1287 /// debug map.
1288 ///
1289 /// \param OutOffset is the offset the cloned DIE in the output
1290 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001291 /// \param PCOffset (while cloning a function scope) is the offset
1292 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001293 ///
1294 /// \returns the root of the cloned tree.
1295 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001296 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001297
1298 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1299
Frederic Riss31da3242015-03-11 18:45:52 +00001300 /// \brief Information gathered and exchanged between the various
1301 /// clone*Attributes helpers about the attributes of a particular DIE.
1302 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001303 const char *Name, *MangledName; ///< Names.
1304 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1305
Frederic Riss31da3242015-03-11 18:45:52 +00001306 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1307 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1308
Frederic Rissbce93ff2015-03-16 02:05:10 +00001309 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1310 bool IsDeclaration; ///< Is this DIE only a declaration?
1311
1312 AttributesInfo()
1313 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1314 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1315 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001316 };
1317
Frederic Rissb8b43d52015-03-04 22:07:44 +00001318 /// \brief Helper for cloneDIE.
1319 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1320 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001321 const AttributeSpec AttrSpec, unsigned AttrSize,
1322 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001323
1324 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001325 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1326 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001327
1328 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001329 unsigned
1330 cloneDieReferenceAttribute(DIE &Die,
1331 const DWARFDebugInfoEntryMinimal &InputDIE,
1332 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001333 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001334
1335 /// \brief Helper for cloneDIE.
1336 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1337 const DWARFFormValue &Val, unsigned AttrSize);
1338
1339 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001340 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1341 const DWARFFormValue &Val,
1342 const CompileUnit &Unit, AttributesInfo &Info);
1343
1344 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001345 unsigned cloneScalarAttribute(DIE &Die,
1346 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001347 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001348 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001349 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001350
Frederic Riss23e20e92015-03-07 01:25:09 +00001351 /// \brief Helper for cloneDIE.
1352 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1353 bool isLittleEndian);
1354
Frederic Rissb8b43d52015-03-04 22:07:44 +00001355 /// \brief Assign an abbreviation number to \p Abbrev
1356 void AssignAbbrev(DIEAbbrev &Abbrev);
1357
1358 /// \brief FoldingSet that uniques the abbreviations.
1359 FoldingSet<DIEAbbrev> AbbreviationsSet;
1360 /// \brief Storage for the unique Abbreviations.
1361 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1362 /// be changed to a vecot of unique_ptrs.
1363 std::vector<DIEAbbrev *> Abbreviations;
1364
Frederic Riss25440872015-03-13 23:30:31 +00001365 /// \brief Compute and emit debug_ranges section for \p Unit, and
1366 /// patch the attributes referencing it.
1367 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1368
1369 /// \brief Generate and emit the DW_AT_ranges attribute for a
1370 /// compile_unit if it had one.
1371 void generateUnitRanges(CompileUnit &Unit) const;
1372
Frederic Riss63786b02015-03-15 20:45:43 +00001373 /// \brief Extract the line tables fromt he original dwarf, extract
1374 /// the relevant parts according to the linked function ranges and
1375 /// emit the result in the debug_line section.
1376 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1377
Frederic Rissbce93ff2015-03-16 02:05:10 +00001378 /// \brief Emit the accelerator entries for \p Unit.
1379 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1380
Frederic Riss5a642072015-06-05 23:06:11 +00001381 /// \brief Patch the frame info for an object file and emit it.
1382 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1383 unsigned AddressSize);
1384
Frederic Rissb8b43d52015-03-04 22:07:44 +00001385 /// \brief DIELoc objects that need to be destructed (but not freed!).
1386 std::vector<DIELoc *> DIELocs;
1387 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1388 std::vector<DIEBlock *> DIEBlocks;
1389 /// \brief Allocator used for all the DIEValue objects.
1390 BumpPtrAllocator DIEAlloc;
1391 /// @}
1392
Frederic Riss1c650942015-07-21 22:41:43 +00001393 /// ODR Contexts for that link.
1394 DeclContextTree ODRContexts;
1395
Frederic Riss1b9da422015-02-13 23:18:29 +00001396 /// \defgroup Helpers Various helper methods.
1397 ///
1398 /// @{
1399 const DWARFDebugInfoEntryMinimal *
Frederic Riss1c650942015-07-21 22:41:43 +00001400 resolveDIEReference(const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001401 const DWARFDebugInfoEntryMinimal &DIE,
1402 CompileUnit *&ReferencedCU);
1403
1404 CompileUnit *getUnitForOffset(unsigned Offset);
1405
Frederic Rissbce93ff2015-03-16 02:05:10 +00001406 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1407 AttributesInfo &Info);
1408
Frederic Riss1b9da422015-02-13 23:18:29 +00001409 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001410 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001411
1412 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001413
1414 /// \brief Attempt to load a debug object from disk.
1415 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1416 DebugMapObject &Obj,
1417 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001418 /// @}
1419
Frederic Riss563cba62015-01-28 22:15:14 +00001420private:
Frederic Rissd3455182015-01-28 18:27:01 +00001421 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001422 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001423 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001424 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001425
1426 /// The units of the current debug map object.
1427 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001428
1429 /// The debug map object curently under consideration.
1430 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001431
1432 /// \brief The Dwarf string pool
1433 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001434
1435 /// \brief This map is keyed by the entry PC of functions in that
1436 /// debug object and the associated value is a pair storing the
1437 /// corresponding end PC and the offset to apply to get the linked
1438 /// address.
1439 ///
1440 /// See startDebugObject() for a more complete description of its use.
1441 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001442
1443 /// \brief The CIEs that have been emitted in the output
1444 /// section. The actual CIE data serves a the key to this StringMap,
1445 /// this takes care of comparing the semantics of CIEs defined in
1446 /// different object files.
1447 StringMap<uint32_t> EmittedCIEs;
1448
1449 /// Offset of the last CIE that has been emitted in the output
1450 /// debug_frame section.
1451 uint32_t LastCIEOffset;
Frederic Rissd3455182015-01-28 18:27:01 +00001452};
1453
Frederic Riss1b9da422015-02-13 23:18:29 +00001454/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1455/// returning our CompileUnit object instead.
1456CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1457 auto CU =
1458 std::upper_bound(Units.begin(), Units.end(), Offset,
1459 [](uint32_t LHS, const CompileUnit &RHS) {
1460 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1461 });
1462 return CU != Units.end() ? &*CU : nullptr;
1463}
1464
1465/// \brief Resolve the DIE attribute reference that has been
1466/// extracted in \p RefValue. The resulting DIE migh be in another
1467/// CompileUnit which is stored into \p ReferencedCU.
1468/// \returns null if resolving fails for any reason.
1469const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
Frederic Riss1c650942015-07-21 22:41:43 +00001470 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001471 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1472 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1473 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1474
1475 if ((RefCU = getUnitForOffset(RefOffset)))
1476 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1477 return RefDie;
1478
1479 reportWarning("could not find referenced DIE", &Unit, &DIE);
1480 return nullptr;
1481}
1482
Frederic Riss1c650942015-07-21 22:41:43 +00001483/// \returns whether the passed \a Attr type might contain a DIE
1484/// reference suitable for ODR uniquing.
1485static bool isODRAttribute(uint16_t Attr) {
1486 switch (Attr) {
1487 default:
1488 return false;
1489 case dwarf::DW_AT_type:
1490 case dwarf::DW_AT_containing_type:
1491 case dwarf::DW_AT_specification:
1492 case dwarf::DW_AT_abstract_origin:
1493 case dwarf::DW_AT_import:
1494 return true;
1495 }
1496 llvm_unreachable("Improper attribute.");
1497}
1498
1499/// Set the last DIE/CU a context was seen in and, possibly invalidate
1500/// the context if it is ambiguous.
1501///
1502/// In the current implementation, we don't handle overloaded
1503/// functions well, because the argument types are not taken into
1504/// account when computing the DeclContext tree.
1505///
1506/// Some of this is mitigated byt using mangled names that do contain
1507/// the arguments types, but sometimes (eg. with function templates)
1508/// we don't have that. In that case, just do not unique anything that
1509/// refers to the contexts we are not able to distinguish.
1510///
1511/// If a context that is not a namespace appears twice in the same CU,
1512/// we know it is ambiguous. Make it invalid.
1513bool DeclContext::setLastSeenDIE(CompileUnit &U,
1514 const DWARFDebugInfoEntryMinimal *Die) {
1515 if (LastSeenCompileUnitID == U.getUniqueID()) {
1516 DWARFUnit &OrigUnit = U.getOrigUnit();
1517 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1518 U.getInfo(FirstIdx).Ctxt = nullptr;
1519 return false;
1520 }
1521
1522 LastSeenCompileUnitID = U.getUniqueID();
1523 LastSeenDIE = Die;
1524 return true;
1525}
1526
1527/// Get the child context of \a Context corresponding to \a DIE.
1528///
1529/// \returns the child context or null if we shouldn't track children
1530/// contexts. It also returns an additional bit meaning 'invalid'. An
1531/// invalid context means it shouldn't be considered for uniquing, but
1532/// its not returning null, because some children of that context
1533/// might be uniquing candidates.
1534/// FIXME: this is for dsymutil-classic compatibility, I don't think
1535/// it buys us much.
1536PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1537 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1538 NonRelocatableStringpool &StringPool) {
1539 unsigned Tag = DIE->getTag();
1540
1541 // FIXME: dsymutil-classic compat: We should bail out here if we
1542 // have a specification or an abstract_origin. We will get the
1543 // parent context wrong here.
1544
1545 switch (Tag) {
1546 default:
1547 // By default stop gathering child contexts.
1548 return PointerIntPair<DeclContext *, 1>(nullptr);
1549 case dwarf::DW_TAG_compile_unit:
1550 // FIXME: Add support for DW_TAG_module.
1551 return PointerIntPair<DeclContext *, 1>(&Context);
1552 case dwarf::DW_TAG_subprogram:
1553 // Do not unique anything inside CU local functions.
1554 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1555 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1556 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1557 dwarf::DW_AT_external, 0))
1558 return PointerIntPair<DeclContext *, 1>(nullptr);
1559 // Fallthrough
1560 case dwarf::DW_TAG_member:
1561 case dwarf::DW_TAG_namespace:
1562 case dwarf::DW_TAG_structure_type:
1563 case dwarf::DW_TAG_class_type:
1564 case dwarf::DW_TAG_union_type:
1565 case dwarf::DW_TAG_enumeration_type:
1566 case dwarf::DW_TAG_typedef:
1567 // Artificial things might be ambiguous, because they might be
1568 // created on demand. For example implicitely defined constructors
1569 // are ambiguous because of the way we identify contexts, and they
1570 // won't be generated everytime everywhere.
1571 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1572 dwarf::DW_AT_artificial, 0))
1573 return PointerIntPair<DeclContext *, 1>(nullptr);
1574 break;
1575 }
1576
1577 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1578 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1579 StringRef NameRef;
1580 StringRef ShortNameRef;
1581 StringRef FileRef;
1582
1583 if (Name)
1584 NameRef = StringPool.internString(Name);
1585 else if (Tag == dwarf::DW_TAG_namespace)
1586 // FIXME: For dsymutil-classic compatibility. I think uniquing
1587 // within anonymous namespaces is wrong. There is no ODR guarantee
1588 // there.
1589 NameRef = StringPool.internString("(anonymous namespace)");
1590
1591 if (ShortName && ShortName != Name)
1592 ShortNameRef = StringPool.internString(ShortName);
1593 else
1594 ShortNameRef = NameRef;
1595
1596 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1597 Tag != dwarf::DW_TAG_union_type &&
1598 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1599 return PointerIntPair<DeclContext *, 1>(nullptr);
1600
1601 std::string File;
1602 unsigned Line = 0;
1603 unsigned ByteSize = 0;
1604
1605 // Gather some discriminating data about the DeclContext we will be
1606 // creating: File, line number and byte size. This shouldn't be
1607 // necessary, because the ODR is just about names, but given that we
1608 // do some approximations with overloaded functions and anonymous
1609 // namespaces, use these additional data points to make the process safer.
1610 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1611 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1612 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1613 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1614 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1615 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1616 &U.getOrigUnit())) {
1617 // FIXME: dsymutil-classic compatibility. I'd rather not
1618 // unique anything in anonymous namespaces, but if we do, then
1619 // verify that the file and line correspond.
1620 if (!Name && Tag == dwarf::DW_TAG_namespace)
1621 FileNum = 1;
1622
1623 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1624 // instead of "" would allow more uniquing, but for now, do
1625 // it this way to match dsymutil-classic.
1626 if (LT->getFileNameByIndex(
1627 FileNum, "",
1628 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1629 File)) {
1630 Line = DIE->getAttributeValueAsUnsignedConstant(
1631 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1632#ifdef HAVE_REALPATH
1633 // Cache the resolved paths, because calling realpath is expansive.
1634 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1635 File = ResolvedPath;
1636 } else {
1637 char RealPath[PATH_MAX + 1];
1638 RealPath[PATH_MAX] = 0;
1639 if (::realpath(File.c_str(), RealPath))
1640 File = RealPath;
1641 U.setResolvedPath(FileNum, File);
1642 }
1643#endif
1644 FileRef = StringPool.internString(File);
1645 }
1646 }
1647 }
1648 }
1649
1650 if (!Line && NameRef.empty())
1651 return PointerIntPair<DeclContext *, 1>(nullptr);
1652
1653 // FIXME: dsymutil-classic compat won't unique the same type
1654 // presented once as a struct and once as a class. Use the Tag in
1655 // the fully qualified name hash to get the same effect.
1656 // We hash NameRef, which is the mangled name, in order to get most
1657 // overloaded functions resolvec correctly.
1658 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1659
1660 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1661 // use the filename.
1662 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1663 Hash = hash_combine(Hash, FileRef);
1664
1665 // Now look if this context already exists.
1666 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1667 auto ContextIter = Contexts.find(&Key);
1668
1669 if (ContextIter == Contexts.end()) {
1670 // The context wasn't found.
1671 bool Inserted;
1672 DeclContext *NewContext =
1673 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1674 Context, DIE, U.getUniqueID());
1675 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1676 assert(Inserted && "Failed to insert DeclContext");
1677 (void)Inserted;
1678 } else if (Tag != dwarf::DW_TAG_namespace &&
1679 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1680 // The context was found, but it is ambiguous with another context
1681 // in the same file. Mark it invalid.
1682 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1683 }
1684
1685 assert(ContextIter != Contexts.end());
1686 // FIXME: dsymutil-classic compatibility. Union types aren't
1687 // uniques, but their children might be.
1688 if ((Tag == dwarf::DW_TAG_subprogram &&
1689 Context.getTag() != dwarf::DW_TAG_structure_type &&
1690 Context.getTag() != dwarf::DW_TAG_class_type) ||
1691 (Tag == dwarf::DW_TAG_union_type))
1692 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1693
1694 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1695}
1696
Frederic Rissbce93ff2015-03-16 02:05:10 +00001697/// \brief Get the potential name and mangled name for the entity
1698/// described by \p Die and store them in \Info if they are not
1699/// already there.
1700/// \returns is a name was found.
1701bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1702 DWARFUnit &U, AttributesInfo &Info) {
1703 // FIXME: a bit wastefull as the first getName might return the
1704 // short name.
1705 if (!Info.MangledName &&
1706 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1707 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1708
1709 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1710 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1711
1712 return Info.Name || Info.MangledName;
1713}
1714
Frederic Riss1b9da422015-02-13 23:18:29 +00001715/// \brief Report a warning to the user, optionaly including
1716/// information about a specific \p DIE related to the warning.
1717void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001718 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001719 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001720 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001721 Context = CurrentDebugObject->getObjectFilename();
1722 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001723
Frederic Rissb9818322015-02-28 00:29:07 +00001724 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001725 return;
1726
1727 errs() << " in DIE:\n";
1728 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1729 6 /* Indent */);
1730}
1731
Frederic Rissc99ea202015-02-28 00:29:11 +00001732bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1733 if (Options.NoOutput)
1734 return true;
1735
Frederic Rissb52cf522015-02-28 00:42:37 +00001736 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001737 return Streamer->init(TheTriple, OutputFilename);
1738}
1739
Frederic Riss563cba62015-01-28 22:15:14 +00001740/// \brief Recursive helper to gather the child->parent relationships in the
1741/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001742static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
Frederic Riss1c650942015-07-21 22:41:43 +00001743 unsigned ParentIdx, CompileUnit &CU,
1744 DeclContext *CurrentDeclContext,
1745 NonRelocatableStringpool &StringPool,
1746 DeclContextTree &Contexts) {
Frederic Riss563cba62015-01-28 22:15:14 +00001747 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001748 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1749
1750 Info.ParentIdx = ParentIdx;
1751 if (CU.hasODR()) {
1752 if (CurrentDeclContext) {
1753 auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1754 DIE, CU, StringPool);
1755 CurrentDeclContext = PtrInvalidPair.getPointer();
1756 Info.Ctxt =
1757 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1758 } else
1759 Info.Ctxt = CurrentDeclContext = nullptr;
1760 }
Frederic Riss563cba62015-01-28 22:15:14 +00001761
1762 if (DIE->hasChildren())
1763 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1764 Child = Child->getSibling())
Frederic Riss1c650942015-07-21 22:41:43 +00001765 gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1766 Contexts);
Frederic Riss563cba62015-01-28 22:15:14 +00001767}
1768
Frederic Riss84c09a52015-02-13 23:18:34 +00001769static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1770 switch (Tag) {
1771 default:
1772 return false;
1773 case dwarf::DW_TAG_subprogram:
1774 case dwarf::DW_TAG_lexical_block:
1775 case dwarf::DW_TAG_subroutine_type:
1776 case dwarf::DW_TAG_structure_type:
1777 case dwarf::DW_TAG_class_type:
1778 case dwarf::DW_TAG_union_type:
1779 return true;
1780 }
1781 llvm_unreachable("Invalid Tag");
1782}
1783
Frederic Riss1c650942015-07-21 22:41:43 +00001784static unsigned getRefAddrSize(const DWARFUnit &U) {
1785 if (U.getVersion() == 2)
1786 return U.getAddressByteSize();
1787 return 4;
1788}
1789
Frederic Riss63786b02015-03-15 20:45:43 +00001790void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001791 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001792 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001793 // Iterate over the debug map entries and put all the ones that are
1794 // functions (because they have a size) into the Ranges map. This
1795 // map is very similar to the FunctionRanges that are stored in each
1796 // unit, with 2 notable differences:
1797 // - obviously this one is global, while the other ones are per-unit.
1798 // - this one contains not only the functions described in the DIE
1799 // tree, but also the ones that are only in the debug map.
1800 // The latter information is required to reproduce dsymutil's logic
1801 // while linking line tables. The cases where this information
1802 // matters look like bugs that need to be investigated, but for now
1803 // we need to reproduce dsymutil's behavior.
1804 // FIXME: Once we understood exactly if that information is needed,
1805 // maybe totally remove this (or try to use it to do a real
1806 // -gline-tables-only on Darwin.
1807 for (const auto &Entry : Obj.symbols()) {
1808 const auto &Mapping = Entry.getValue();
1809 if (Mapping.Size)
1810 Ranges[Mapping.ObjectAddress] = std::make_pair(
1811 Mapping.ObjectAddress + Mapping.Size,
1812 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1813 }
Frederic Riss563cba62015-01-28 22:15:14 +00001814}
1815
Frederic Riss1036e642015-02-13 23:18:22 +00001816void DwarfLinker::endDebugObject() {
1817 Units.clear();
1818 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001819 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001820
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001821 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1822 (*I)->~DIEBlock();
1823 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1824 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001825
1826 DIEBlocks.clear();
1827 DIELocs.clear();
1828 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001829}
1830
1831/// \brief Iterate over the relocations of the given \p Section and
1832/// store the ones that correspond to debug map entries into the
1833/// ValidRelocs array.
1834void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1835 const object::MachOObjectFile &Obj,
1836 const DebugMapObject &DMO) {
1837 StringRef Contents;
1838 Section.getContents(Contents);
1839 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1840
1841 for (const object::RelocationRef &Reloc : Section.relocations()) {
1842 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1843 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1844 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001845 uint64_t Offset64 = Reloc.getOffset();
1846 if ((RelocSize != 4 && RelocSize != 8)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001847 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001848 continue;
1849 }
1850 uint32_t Offset = Offset64;
1851 // Mach-o uses REL relocations, the addend is at the relocation offset.
1852 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1853
1854 auto Sym = Reloc.getSymbol();
1855 if (Sym != Obj.symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001856 ErrorOr<StringRef> SymbolName = Sym->getName();
1857 if (!SymbolName) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001858 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001859 continue;
1860 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001861 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001862 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1863 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1864 // Do not store the addend. The addend was the address of the
1865 // symbol in the object file, the address in the binary that is
1866 // stored in the debug map doesn't need to be offseted.
1867 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1868 }
1869 }
1870}
1871
1872/// \brief Dispatch the valid relocation finding logic to the
1873/// appropriate handler depending on the object file format.
1874bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1875 const object::ObjectFile &Obj,
1876 const DebugMapObject &DMO) {
1877 // Dispatch to the right handler depending on the file type.
1878 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1879 findValidRelocsMachO(Section, *MachOObj, DMO);
1880 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001881 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001882
1883 if (ValidRelocs.empty())
1884 return false;
1885
1886 // Sort the relocations by offset. We will walk the DIEs linearly in
1887 // the file, this allows us to just keep an index in the relocation
1888 // array that we advance during our walk, rather than resorting to
1889 // some associative container. See DwarfLinker::NextValidReloc.
1890 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1891 return true;
1892}
1893
1894/// \brief Look for relocations in the debug_info section that match
1895/// entries in the debug map. These relocations will drive the Dwarf
1896/// link by indicating which DIEs refer to symbols present in the
1897/// linked binary.
1898/// \returns wether there are any valid relocations in the debug info.
1899bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1900 const DebugMapObject &DMO) {
1901 // Find the debug_info section.
1902 for (const object::SectionRef &Section : Obj.sections()) {
1903 StringRef SectionName;
1904 Section.getName(SectionName);
1905 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1906 if (SectionName != "debug_info")
1907 continue;
1908 return findValidRelocs(Section, Obj, DMO);
1909 }
1910 return false;
1911}
Frederic Riss563cba62015-01-28 22:15:14 +00001912
Frederic Riss84c09a52015-02-13 23:18:34 +00001913/// \brief Checks that there is a relocation against an actual debug
1914/// map entry between \p StartOffset and \p NextOffset.
1915///
1916/// This function must be called with offsets in strictly ascending
1917/// order because it never looks back at relocations it already 'went past'.
1918/// \returns true and sets Info.InDebugMap if it is the case.
1919bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1920 CompileUnit::DIEInfo &Info) {
1921 assert(NextValidReloc == 0 ||
1922 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1923 if (NextValidReloc >= ValidRelocs.size())
1924 return false;
1925
1926 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1927
1928 // We might need to skip some relocs that we didn't consider. For
1929 // example the high_pc of a discarded DIE might contain a reloc that
1930 // is in the list because it actually corresponds to the start of a
1931 // function that is in the debug map.
1932 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1933 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1934
1935 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1936 return false;
1937
1938 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001939 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissb9818322015-02-28 00:29:07 +00001940 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001941 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1942 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001943 uint64_t(Mapping.ObjectAddress),
1944 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001945
Frederic Rissf37964c2015-06-05 20:27:07 +00001946 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1947 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001948 Info.InDebugMap = true;
1949 return true;
1950}
1951
1952/// \brief Get the starting and ending (exclusive) offset for the
1953/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1954/// supposed to point to the position of the first attribute described
1955/// by \p Abbrev.
1956/// \return [StartOffset, EndOffset) as a pair.
1957static std::pair<uint32_t, uint32_t>
1958getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1959 unsigned Offset, const DWARFUnit &Unit) {
1960 DataExtractor Data = Unit.getDebugInfoExtractor();
1961
1962 for (unsigned i = 0; i < Idx; ++i)
1963 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1964
1965 uint32_t End = Offset;
1966 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1967
1968 return std::make_pair(Offset, End);
1969}
1970
1971/// \brief Check if a variable describing DIE should be kept.
1972/// \returns updated TraversalFlags.
1973unsigned DwarfLinker::shouldKeepVariableDIE(
1974 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1975 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1976 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1977
1978 // Global variables with constant value can always be kept.
1979 if (!(Flags & TF_InFunctionScope) &&
1980 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1981 MyInfo.InDebugMap = true;
1982 return Flags | TF_Keep;
1983 }
1984
1985 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1986 if (LocationIdx == -1U)
1987 return Flags;
1988
1989 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1990 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1991 uint32_t LocationOffset, LocationEndOffset;
1992 std::tie(LocationOffset, LocationEndOffset) =
1993 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1994
1995 // See if there is a relocation to a valid debug map entry inside
1996 // this variable's location. The order is important here. We want to
1997 // always check in the variable has a valid relocation, so that the
1998 // DIEInfo is filled. However, we don't want a static variable in a
1999 // function to force us to keep the enclosing function.
2000 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
2001 (Flags & TF_InFunctionScope))
2002 return Flags;
2003
Frederic Rissb9818322015-02-28 00:29:07 +00002004 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002005 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2006
2007 return Flags | TF_Keep;
2008}
2009
2010/// \brief Check if a function describing DIE should be kept.
2011/// \returns updated TraversalFlags.
2012unsigned DwarfLinker::shouldKeepSubprogramDIE(
2013 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2014 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2015 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2016
2017 Flags |= TF_InFunctionScope;
2018
2019 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2020 if (LowPcIdx == -1U)
2021 return Flags;
2022
2023 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2024 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2025 uint32_t LowPcOffset, LowPcEndOffset;
2026 std::tie(LowPcOffset, LowPcEndOffset) =
2027 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2028
2029 uint64_t LowPc =
2030 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2031 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2032 if (LowPc == -1ULL ||
2033 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
2034 return Flags;
2035
Frederic Rissb9818322015-02-28 00:29:07 +00002036 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002037 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2038
Frederic Riss1af75f72015-03-12 18:45:10 +00002039 Flags |= TF_Keep;
2040
2041 DWARFFormValue HighPcValue;
2042 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2043 reportWarning("Function without high_pc. Range will be discarded.\n",
2044 &OrigUnit, &DIE);
2045 return Flags;
2046 }
2047
2048 uint64_t HighPc;
2049 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2050 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2051 } else {
2052 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2053 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2054 }
2055
Frederic Riss63786b02015-03-15 20:45:43 +00002056 // Replace the debug map range with a more accurate one.
2057 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002058 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2059 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002060}
2061
2062/// \brief Check if a DIE should be kept.
2063/// \returns updated TraversalFlags.
2064unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
2065 CompileUnit &Unit,
2066 CompileUnit::DIEInfo &MyInfo,
2067 unsigned Flags) {
2068 switch (DIE.getTag()) {
2069 case dwarf::DW_TAG_constant:
2070 case dwarf::DW_TAG_variable:
2071 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
2072 case dwarf::DW_TAG_subprogram:
2073 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
2074 case dwarf::DW_TAG_module:
2075 case dwarf::DW_TAG_imported_module:
2076 case dwarf::DW_TAG_imported_declaration:
2077 case dwarf::DW_TAG_imported_unit:
2078 // We always want to keep these.
2079 return Flags | TF_Keep;
2080 }
2081
2082 return Flags;
2083}
2084
Frederic Riss84c09a52015-02-13 23:18:34 +00002085/// \brief Mark the passed DIE as well as all the ones it depends on
2086/// as kept.
2087///
2088/// This function is called by lookForDIEsToKeep on DIEs that are
2089/// newly discovered to be needed in the link. It recursively calls
2090/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2091/// TraversalFlags to inform it that it's not doing the primary DIE
2092/// tree walk.
2093void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
2094 CompileUnit::DIEInfo &MyInfo,
2095 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002096 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002097 const DWARFUnit &Unit = CU.getOrigUnit();
2098 MyInfo.Keep = true;
2099
2100 // First mark all the parent chain as kept.
2101 unsigned AncestorIdx = MyInfo.ParentIdx;
2102 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002103 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Frederic Riss84c09a52015-02-13 23:18:34 +00002104 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002105 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002106 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2107 }
2108
2109 // Then we need to mark all the DIEs referenced by this DIE's
2110 // attributes as kept.
2111 DataExtractor Data = Unit.getDebugInfoExtractor();
2112 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2113 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2114
2115 // Mark all DIEs referenced through atttributes as kept.
2116 for (const auto &AttrSpec : Abbrev->attributes()) {
2117 DWARFFormValue Val(AttrSpec.Form);
2118
2119 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2120 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2121 continue;
2122 }
2123
2124 Val.extractValue(Data, &Offset, &Unit);
2125 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002126 if (const auto *RefDIE =
2127 resolveDIEReference(Val, Unit, DIE, ReferencedCU)) {
2128 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2129 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2130 // If the referenced DIE has a DeclContext that has already been
2131 // emitted, then do not keep the one in this CU. We'll link to
2132 // the canonical DIE in cloneDieReferenceAttribute.
2133 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2134 // be necessary and could be advantageously replaced by
2135 // ReferencedCU->hasODR() && CU.hasODR().
2136 // FIXME: compatibility with dsymutil-classic. There is no
2137 // reason not to unique ref_addr references.
2138 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2139 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2140 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2141 continue;
2142
2143 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Frederic Riss84c09a52015-02-13 23:18:34 +00002144 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002145 TF_Keep | TF_DependencyWalk | ODRFlag);
2146 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002147 }
2148}
2149
2150/// \brief Recursively walk the \p DIE tree and look for DIEs to
2151/// keep. Store that information in \p CU's DIEInfo.
2152///
2153/// This function is the entry point of the DIE selection
2154/// algorithm. It is expected to walk the DIE tree in file order and
2155/// (though the mediation of its helper) call hasValidRelocation() on
2156/// each DIE that might be a 'root DIE' (See DwarfLinker class
2157/// comment).
2158/// While walking the dependencies of root DIEs, this function is
2159/// also called, but during these dependency walks the file order is
2160/// not respected. The TF_DependencyWalk flag tells us which kind of
2161/// traversal we are currently doing.
2162void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
2163 const DebugMapObject &DMO, CompileUnit &CU,
2164 unsigned Flags) {
2165 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
2166 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2167 bool AlreadyKept = MyInfo.Keep;
2168
2169 // If the Keep flag is set, we are marking a required DIE's
2170 // dependencies. If our target is already marked as kept, we're all
2171 // set.
2172 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2173 return;
2174
2175 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2176 // because it would screw up the relocation finding logic.
2177 if (!(Flags & TF_DependencyWalk))
2178 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
2179
2180 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002181 if (!AlreadyKept && (Flags & TF_Keep)) {
2182 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2183 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, UseOdr);
2184 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002185 // The TF_ParentWalk flag tells us that we are currently walking up
2186 // the parent chain of a required DIE, and we don't want to mark all
2187 // the children of the parents as kept (consider for example a
2188 // DW_TAG_namespace node in the parent chain). There are however a
2189 // set of DIE types for which we want to ignore that directive and still
2190 // walk their children.
2191 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
2192 Flags &= ~TF_ParentWalk;
2193
2194 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
2195 return;
2196
2197 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
2198 Child = Child->getSibling())
2199 lookForDIEsToKeep(*Child, DMO, CU, Flags);
2200}
2201
Frederic Rissb8b43d52015-03-04 22:07:44 +00002202/// \brief Assign an abbreviation numer to \p Abbrev.
2203///
2204/// Our DIEs get freed after every DebugMapObject has been processed,
2205/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2206/// the instances hold by the DIEs. When we encounter an abbreviation
2207/// that we don't know, we create a permanent copy of it.
2208void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2209 // Check the set for priors.
2210 FoldingSetNodeID ID;
2211 Abbrev.Profile(ID);
2212 void *InsertToken;
2213 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2214
2215 // If it's newly added.
2216 if (InSet) {
2217 // Assign existing abbreviation number.
2218 Abbrev.setNumber(InSet->getNumber());
2219 } else {
2220 // Add to abbreviation list.
2221 Abbreviations.push_back(
2222 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2223 for (const auto &Attr : Abbrev.getData())
2224 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2225 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2226 // Assign the unique abbreviation number.
2227 Abbrev.setNumber(Abbreviations.size());
2228 Abbreviations.back()->setNumber(Abbreviations.size());
2229 }
2230}
2231
2232/// \brief Clone a string attribute described by \p AttrSpec and add
2233/// it to \p Die.
2234/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00002235unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
2236 const DWARFFormValue &Val,
2237 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002238 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002239 const char *String = *Val.getAsCString(&U);
2240 unsigned Offset = StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002241 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002242 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002243 return 4;
2244}
2245
2246/// \brief Clone an attribute referencing another DIE and add
2247/// it to \p Die.
2248/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00002249unsigned DwarfLinker::cloneDieReferenceAttribute(
2250 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2251 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002252 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002253 const DWARFUnit &U = Unit.getOrigUnit();
2254 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002255 DIE *NewRefDie = nullptr;
2256 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002257 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002258
Frederic Riss1c650942015-07-21 22:41:43 +00002259 const DWARFDebugInfoEntryMinimal *RefDie =
2260 resolveDIEReference(Val, U, InputDIE, RefUnit);
2261
2262 // If the referenced DIE is not found, drop the attribute.
2263 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002264 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002265
2266 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2267 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002268
2269 // If we already have emitted an equivalent DeclContext, just point
2270 // at it.
2271 if (isODRAttribute(AttrSpec.Attr)) {
2272 Ctxt = RefInfo.Ctxt;
2273 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2274 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2275 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2276 dwarf::DW_FORM_ref_addr, Attr);
2277 return getRefAddrSize(U);
2278 }
2279 }
2280
Frederic Riss9833de62015-03-06 23:22:53 +00002281 if (!RefInfo.Clone) {
2282 assert(Ref > InputDIE.getOffset());
2283 // We haven't cloned this DIE yet. Just create an empty one and
2284 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002285 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002286 }
2287 NewRefDie = RefInfo.Clone;
2288
Frederic Riss1c650942015-07-21 22:41:43 +00002289 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2290 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002291 // We cannot currently rely on a DIEEntry to emit ref_addr
2292 // references, because the implementation calls back to DwarfDebug
2293 // to find the unit offset. (We don't have a DwarfDebug)
2294 // FIXME: we should be able to design DIEEntry reliance on
2295 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002296 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002297 if (Ref < InputDIE.getOffset()) {
2298 // We must have already cloned that DIE.
2299 uint32_t NewRefOffset =
2300 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002301 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002302 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2303 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002304 } else {
2305 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002306 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002307 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002308 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002309 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2310 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002311 }
Frederic Riss1c650942015-07-21 22:41:43 +00002312 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002313 }
2314
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002315 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2316 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002317 return AttrSize;
2318}
2319
2320/// \brief Clone an attribute of block form (locations, constants) and add
2321/// it to \p Die.
2322/// \returns the size of the new attribute.
2323unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
2324 const DWARFFormValue &Val,
2325 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002326 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002327 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002328 DIELoc *Loc = nullptr;
2329 DIEBlock *Block = nullptr;
2330 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002331 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002332 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002333 DIELocs.push_back(Loc);
2334 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002335 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002336 DIEBlocks.push_back(Block);
2337 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002338 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2339 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002340
2341 if (Loc)
2342 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2343 dwarf::Form(AttrSpec.Form), Loc);
2344 else
2345 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2346 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002347 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2348 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002349 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2350 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002351 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2352 // the DIE class, this if could be replaced by
2353 // Attr->setSize(Bytes.size()).
2354 if (Streamer) {
2355 if (Loc)
2356 Loc->ComputeSize(&Streamer->getAsmPrinter());
2357 else
2358 Block->ComputeSize(&Streamer->getAsmPrinter());
2359 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002360 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002361 return AttrSize;
2362}
2363
Frederic Riss31da3242015-03-11 18:45:52 +00002364/// \brief Clone an address attribute and add it to \p Die.
2365/// \returns the size of the new attribute.
2366unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
2367 const DWARFFormValue &Val,
2368 const CompileUnit &Unit,
2369 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002370 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002371 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2372 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2373 Die.getTag() == dwarf::DW_TAG_lexical_block)
2374 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002375 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2376 Addr = Unit.getLowPc();
2377 if (Addr == UINT64_MAX)
2378 return 0;
2379 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002380 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002381 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002382 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2383 if (uint64_t HighPc = Unit.getHighPc())
2384 Addr = HighPc;
2385 else
2386 return 0;
2387 } else
2388 // If we have a high_pc recorded for the input DIE, use
2389 // it. Otherwise (when no relocations where applied) just use the
2390 // one we just decoded.
2391 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002392 }
2393
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002394 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002395 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002396 return Unit.getOrigUnit().getAddressByteSize();
2397}
2398
Frederic Rissb8b43d52015-03-04 22:07:44 +00002399/// \brief Clone a scalar attribute and add it to \p Die.
2400/// \returns the size of the new attribute.
2401unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002402 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002403 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002404 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002405 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002406 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2407 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2408 if (Unit.getLowPc() == -1ULL)
2409 return 0;
2410 // Dwarf >= 4 high_pc is an size, not an address.
2411 Value = Unit.getHighPc() - Unit.getLowPc();
2412 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002413 Value = *Val.getAsSectionOffset();
2414 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2415 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002416 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2417 Value = *OptionalValue;
2418 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002419 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2420 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002421 return 0;
2422 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002423 PatchLocation Patch =
2424 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2425 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002426 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002427 Unit.noteRangeAttribute(Die, Patch);
Frederic Rissdfb97902015-03-14 15:49:07 +00002428 // A more generic way to check for location attributes would be
2429 // nice, but it's very unlikely that any other attribute needs a
2430 // location list.
2431 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2432 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002433 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002434 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2435 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002436
Frederic Rissb8b43d52015-03-04 22:07:44 +00002437 return AttrSize;
2438}
2439
2440/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2441/// value \p Val, and add it to \p Die.
2442/// \returns the size of the cloned attribute.
2443unsigned DwarfLinker::cloneAttribute(DIE &Die,
2444 const DWARFDebugInfoEntryMinimal &InputDIE,
2445 CompileUnit &Unit,
2446 const DWARFFormValue &Val,
2447 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00002448 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002449 const DWARFUnit &U = Unit.getOrigUnit();
2450
2451 switch (AttrSpec.Form) {
2452 case dwarf::DW_FORM_strp:
2453 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002454 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002455 case dwarf::DW_FORM_ref_addr:
2456 case dwarf::DW_FORM_ref1:
2457 case dwarf::DW_FORM_ref2:
2458 case dwarf::DW_FORM_ref4:
2459 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002460 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002461 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002462 case dwarf::DW_FORM_block:
2463 case dwarf::DW_FORM_block1:
2464 case dwarf::DW_FORM_block2:
2465 case dwarf::DW_FORM_block4:
2466 case dwarf::DW_FORM_exprloc:
2467 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2468 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002469 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002470 case dwarf::DW_FORM_data1:
2471 case dwarf::DW_FORM_data2:
2472 case dwarf::DW_FORM_data4:
2473 case dwarf::DW_FORM_data8:
2474 case dwarf::DW_FORM_udata:
2475 case dwarf::DW_FORM_sdata:
2476 case dwarf::DW_FORM_sec_offset:
2477 case dwarf::DW_FORM_flag:
2478 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002479 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2480 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002481 default:
2482 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2483 &InputDIE);
2484 }
2485
2486 return 0;
2487}
2488
Frederic Riss23e20e92015-03-07 01:25:09 +00002489/// \brief Apply the valid relocations found by findValidRelocs() to
2490/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2491/// in the debug_info section.
2492///
2493/// Like for findValidRelocs(), this function must be called with
2494/// monotonic \p BaseOffset values.
2495///
2496/// \returns wether any reloc has been applied.
2497bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2498 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002499 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002500 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2501 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002502 if (NextValidReloc >= ValidRelocs.size())
2503 return false;
2504
2505 // Skip relocs that haven't been applied.
2506 while (NextValidReloc < ValidRelocs.size() &&
2507 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2508 ++NextValidReloc;
2509
2510 bool Applied = false;
2511 uint64_t EndOffset = BaseOffset + Data.size();
2512 while (NextValidReloc < ValidRelocs.size() &&
2513 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2514 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2515 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2516 assert(ValidReloc.Offset - BaseOffset < Data.size());
2517 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2518 char Buf[8];
2519 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2520 Value += ValidReloc.Addend;
2521 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2522 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2523 Buf[i] = uint8_t(Value >> (Index * 8));
2524 }
2525 assert(ValidReloc.Size <= sizeof(Buf));
2526 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2527 Applied = true;
2528 }
2529
2530 return Applied;
2531}
2532
Frederic Rissbce93ff2015-03-16 02:05:10 +00002533static bool isTypeTag(uint16_t Tag) {
2534 switch (Tag) {
2535 case dwarf::DW_TAG_array_type:
2536 case dwarf::DW_TAG_class_type:
2537 case dwarf::DW_TAG_enumeration_type:
2538 case dwarf::DW_TAG_pointer_type:
2539 case dwarf::DW_TAG_reference_type:
2540 case dwarf::DW_TAG_string_type:
2541 case dwarf::DW_TAG_structure_type:
2542 case dwarf::DW_TAG_subroutine_type:
2543 case dwarf::DW_TAG_typedef:
2544 case dwarf::DW_TAG_union_type:
2545 case dwarf::DW_TAG_ptr_to_member_type:
2546 case dwarf::DW_TAG_set_type:
2547 case dwarf::DW_TAG_subrange_type:
2548 case dwarf::DW_TAG_base_type:
2549 case dwarf::DW_TAG_const_type:
2550 case dwarf::DW_TAG_constant:
2551 case dwarf::DW_TAG_file_type:
2552 case dwarf::DW_TAG_namelist:
2553 case dwarf::DW_TAG_packed_type:
2554 case dwarf::DW_TAG_volatile_type:
2555 case dwarf::DW_TAG_restrict_type:
2556 case dwarf::DW_TAG_interface_type:
2557 case dwarf::DW_TAG_unspecified_type:
2558 case dwarf::DW_TAG_shared_type:
2559 return true;
2560 default:
2561 break;
2562 }
2563 return false;
2564}
2565
Frederic Rissb8b43d52015-03-04 22:07:44 +00002566/// \brief Recursively clone \p InputDIE's subtrees that have been
2567/// selected to appear in the linked output.
2568///
2569/// \param OutOffset is the Offset where the newly created DIE will
2570/// lie in the linked compile unit.
2571///
2572/// \returns the cloned DIE object or null if nothing was selected.
2573DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002574 CompileUnit &Unit, int64_t PCOffset,
2575 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002576 DWARFUnit &U = Unit.getOrigUnit();
2577 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002578 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002579
2580 // Should the DIE appear in the output?
2581 if (!Unit.getInfo(Idx).Keep)
2582 return nullptr;
2583
2584 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002585 // The DIE might have been already created by a forward reference
2586 // (see cloneDieReferenceAttribute()).
2587 DIE *Die = Info.Clone;
2588 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002589 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002590 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002591 Die->setOffset(OutOffset);
Frederic Riss1c650942015-07-21 22:41:43 +00002592 if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2593 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2594 !Info.Ctxt->getCanonicalDIEOffset()) {
2595 // We are about to emit a DIE that is the root of its own valid
2596 // DeclContext tree. Make the current offset the canonical offset
2597 // for this context.
2598 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2599 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002600
2601 // Extract and clone every attribute.
2602 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002603 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002604 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002605
2606 // We could copy the data only if we need to aply a relocation to
2607 // it. After testing, it seems there is no performance downside to
2608 // doing the copy unconditionally, and it makes the code simpler.
2609 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2610 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2611 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002612 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2613 // If we applied relocations, we store the value of high_pc that was
2614 // potentially stored in the input DIE. If high_pc is an address
2615 // (Dwarf version == 2), then it might have been relocated to a
2616 // totally unrelated value (because the end address in the object
2617 // file might be start address of another function which got moved
2618 // independantly by the linker). The computation of the actual
2619 // high_pc value is done in cloneAddressAttribute().
2620 AttrInfo.OrigHighPc =
2621 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2622 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002623
2624 // Reset the Offset to 0 as we will be working on the local copy of
2625 // the data.
2626 Offset = 0;
2627
Frederic Rissb8b43d52015-03-04 22:07:44 +00002628 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2629 Offset += getULEB128Size(Abbrev->getCode());
2630
Frederic Riss31da3242015-03-11 18:45:52 +00002631 // We are entering a subprogram. Get and propagate the PCOffset.
2632 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2633 PCOffset = Info.AddrAdjust;
2634 AttrInfo.PCOffset = PCOffset;
2635
Frederic Rissb8b43d52015-03-04 22:07:44 +00002636 for (const auto &AttrSpec : Abbrev->attributes()) {
2637 DWARFFormValue Val(AttrSpec.Form);
2638 uint32_t AttrSize = Offset;
2639 Val.extractValue(Data, &Offset, &U);
2640 AttrSize = Offset - AttrSize;
2641
Frederic Riss31da3242015-03-11 18:45:52 +00002642 OutOffset +=
2643 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002644 }
2645
Frederic Rissbce93ff2015-03-16 02:05:10 +00002646 // Look for accelerator entries.
2647 uint16_t Tag = InputDIE.getTag();
2648 // FIXME: This is slightly wrong. An inline_subroutine without a
2649 // low_pc, but with AT_ranges might be interesting to get into the
2650 // accelerator tables too. For now stick with dsymutil's behavior.
2651 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2652 Tag != dwarf::DW_TAG_compile_unit &&
2653 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2654 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2655 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2656 AttrInfo.MangledNameOffset,
2657 Tag == dwarf::DW_TAG_inlined_subroutine);
2658 if (AttrInfo.Name)
2659 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2660 Tag == dwarf::DW_TAG_inlined_subroutine);
2661 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2662 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2663 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2664 }
2665
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002666 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002667 // If a scope DIE is kept, we must have kept at least one child. If
2668 // it's not the case, we'll just be emitting one wasteful end of
2669 // children marker, but things won't break.
2670 if (InputDIE.hasChildren())
2671 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2672 // Assign a permanent abbrev number
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002673 AssignAbbrev(NewAbbrev);
2674 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002675
2676 // Add the size of the abbreviation number to the output offset.
2677 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2678
2679 if (!Abbrev->hasChildren()) {
2680 // Update our size.
2681 Die->setSize(OutOffset - Die->getOffset());
2682 return Die;
2683 }
2684
2685 // Recursively clone children.
2686 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2687 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002688 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002689 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002690 OutOffset = Clone->getOffset() + Clone->getSize();
2691 }
2692 }
2693
2694 // Account for the end of children marker.
2695 OutOffset += sizeof(int8_t);
2696 // Update our size.
2697 Die->setSize(OutOffset - Die->getOffset());
2698 return Die;
2699}
2700
Frederic Riss25440872015-03-13 23:30:31 +00002701/// \brief Patch the input object file relevant debug_ranges entries
2702/// and emit them in the output file. Update the relevant attributes
2703/// to point at the new entries.
2704void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2705 DWARFContext &OrigDwarf) const {
2706 DWARFDebugRangeList RangeList;
2707 const auto &FunctionRanges = Unit.getFunctionRanges();
2708 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2709 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2710 OrigDwarf.isLittleEndian(), AddressSize);
2711 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2712 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002713 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002714 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2715 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2716 // Ranges addresses are based on the unit's low_pc. Compute the
2717 // offset we need to apply to adapt to the the new unit's low_pc.
2718 int64_t UnitPcOffset = 0;
2719 if (OrigLowPc != -1ULL)
2720 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2721
2722 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002723 uint32_t Offset = RangeAttribute.get();
2724 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002725 RangeList.extract(RangeExtractor, &Offset);
2726 const auto &Entries = RangeList.getEntries();
2727 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2728
2729 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2730 First.StartAddress >= CurrRange.stop()) {
2731 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2732 if (CurrRange == InvalidRange ||
2733 CurrRange.start() > First.StartAddress + OrigLowPc) {
2734 reportWarning("no mapping for range.");
2735 continue;
2736 }
2737 }
2738
2739 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2740 AddressSize);
2741 }
2742}
2743
Frederic Riss563b1b02015-03-14 03:46:51 +00002744/// \brief Generate the debug_aranges entries for \p Unit and if the
2745/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2746/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002747/// FIXME: this could actually be done right in patchRangesForUnit,
2748/// but for the sake of initial bit-for-bit compatibility with legacy
2749/// dsymutil, we have to do it in a delayed pass.
2750void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002751 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002752 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002753 Attr->set(Streamer->getRangesSectionSize());
2754 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002755}
2756
Frederic Riss63786b02015-03-15 20:45:43 +00002757/// \brief Insert the new line info sequence \p Seq into the current
2758/// set of already linked line info \p Rows.
2759static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2760 std::vector<DWARFDebugLine::Row> &Rows) {
2761 if (Seq.empty())
2762 return;
2763
2764 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2765 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2766 Seq.clear();
2767 return;
2768 }
2769
2770 auto InsertPoint = std::lower_bound(
2771 Rows.begin(), Rows.end(), Seq.front(),
2772 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2773 return LHS.Address < RHS.Address;
2774 });
2775
2776 // FIXME: this only removes the unneeded end_sequence if the
2777 // sequences have been inserted in order. using a global sort like
2778 // described in patchLineTableForUnit() and delaying the end_sequene
2779 // elimination to emitLineTableForUnit() we can get rid of all of them.
2780 if (InsertPoint != Rows.end() &&
2781 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2782 *InsertPoint = Seq.front();
2783 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2784 } else {
2785 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2786 }
2787
2788 Seq.clear();
2789}
2790
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002791static void patchStmtList(DIE &Die, DIEInteger Offset) {
2792 for (auto &V : Die.values())
2793 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002794 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002795 return;
2796 }
2797
2798 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2799}
2800
Frederic Riss63786b02015-03-15 20:45:43 +00002801/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2802/// recreate a relocated version of these for the address ranges that
2803/// are present in the binary.
2804void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2805 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002806 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002807 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2808 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2809 if (StmtList == -1ULL)
2810 return;
2811
2812 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002813 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2814 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002815
2816 // Parse the original line info for the unit.
2817 DWARFDebugLine::LineTable LineTable;
2818 uint32_t StmtOffset = StmtList;
2819 StringRef LineData = OrigDwarf.getLineSection().Data;
2820 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2821 Unit.getOrigUnit().getAddressByteSize());
2822 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2823 &StmtOffset);
2824
2825 // This vector is the output line table.
2826 std::vector<DWARFDebugLine::Row> NewRows;
2827 NewRows.reserve(LineTable.Rows.size());
2828
2829 // Current sequence of rows being extracted, before being inserted
2830 // in NewRows.
2831 std::vector<DWARFDebugLine::Row> Seq;
2832 const auto &FunctionRanges = Unit.getFunctionRanges();
2833 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2834
2835 // FIXME: This logic is meant to generate exactly the same output as
2836 // Darwin's classic dsynutil. There is a nicer way to implement this
2837 // by simply putting all the relocated line info in NewRows and simply
2838 // sorting NewRows before passing it to emitLineTableForUnit. This
2839 // should be correct as sequences for a function should stay
2840 // together in the sorted output. There are a few corner cases that
2841 // look suspicious though, and that required to implement the logic
2842 // this way. Revisit that once initial validation is finished.
2843
2844 // Iterate over the object file line info and extract the sequences
2845 // that correspond to linked functions.
2846 for (auto &Row : LineTable.Rows) {
2847 // Check wether we stepped out of the range. The range is
2848 // half-open, but consider accept the end address of the range if
2849 // it is marked as end_sequence in the input (because in that
2850 // case, the relocation offset is accurate and that entry won't
2851 // serve as the start of another function).
2852 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2853 Row.Address > CurrRange.stop() ||
2854 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2855 // We just stepped out of a known range. Insert a end_sequence
2856 // corresponding to the end of the range.
2857 uint64_t StopAddress = CurrRange != InvalidRange
2858 ? CurrRange.stop() + CurrRange.value()
2859 : -1ULL;
2860 CurrRange = FunctionRanges.find(Row.Address);
2861 bool CurrRangeValid =
2862 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2863 if (!CurrRangeValid) {
2864 CurrRange = InvalidRange;
2865 if (StopAddress != -1ULL) {
2866 // Try harder by looking in the DebugMapObject function
2867 // ranges map. There are corner cases where this finds a
2868 // valid entry. It's unclear if this is right or wrong, but
2869 // for now do as dsymutil.
2870 // FIXME: Understand exactly what cases this addresses and
2871 // potentially remove it along with the Ranges map.
2872 auto Range = Ranges.lower_bound(Row.Address);
2873 if (Range != Ranges.begin() && Range != Ranges.end())
2874 --Range;
2875
2876 if (Range != Ranges.end() && Range->first <= Row.Address &&
2877 Range->second.first >= Row.Address) {
2878 StopAddress = Row.Address + Range->second.second;
2879 }
2880 }
2881 }
2882 if (StopAddress != -1ULL && !Seq.empty()) {
2883 // Insert end sequence row with the computed end address, but
2884 // the same line as the previous one.
2885 Seq.emplace_back(Seq.back());
2886 Seq.back().Address = StopAddress;
2887 Seq.back().EndSequence = 1;
2888 Seq.back().PrologueEnd = 0;
2889 Seq.back().BasicBlock = 0;
2890 Seq.back().EpilogueBegin = 0;
2891 insertLineSequence(Seq, NewRows);
2892 }
2893
2894 if (!CurrRangeValid)
2895 continue;
2896 }
2897
2898 // Ignore empty sequences.
2899 if (Row.EndSequence && Seq.empty())
2900 continue;
2901
2902 // Relocate row address and add it to the current sequence.
2903 Row.Address += CurrRange.value();
2904 Seq.emplace_back(Row);
2905
2906 if (Row.EndSequence)
2907 insertLineSequence(Seq, NewRows);
2908 }
2909
2910 // Finished extracting, now emit the line tables.
2911 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2912 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2913 // prologue over and that works because we act as both producer and
2914 // consumer. It would be nicer to have a real configurable line
2915 // table emitter.
2916 if (LineTable.Prologue.Version != 2 ||
2917 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2918 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2919 LineTable.Prologue.OpcodeBase != 13)
2920 reportWarning("line table paramters mismatch. Cannot emit.");
2921 else
2922 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2923 LineTable.Prologue.MinInstLength, NewRows,
2924 Unit.getOrigUnit().getAddressByteSize());
2925}
2926
Frederic Rissbce93ff2015-03-16 02:05:10 +00002927void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2928 Streamer->emitPubNamesForUnit(Unit);
2929 Streamer->emitPubTypesForUnit(Unit);
2930}
2931
Frederic Riss5a642072015-06-05 23:06:11 +00002932/// \brief Read the frame info stored in the object, and emit the
2933/// patched frame descriptions for the linked binary.
2934///
2935/// This is actually pretty easy as the data of the CIEs and FDEs can
2936/// be considered as black boxes and moved as is. The only thing to do
2937/// is to patch the addresses in the headers.
2938void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2939 DWARFContext &OrigDwarf,
2940 unsigned AddrSize) {
2941 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2942 if (FrameData.empty())
2943 return;
2944
2945 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2946 uint32_t InputOffset = 0;
2947
2948 // Store the data of the CIEs defined in this object, keyed by their
2949 // offsets.
2950 DenseMap<uint32_t, StringRef> LocalCIES;
2951
2952 while (Data.isValidOffset(InputOffset)) {
2953 uint32_t EntryOffset = InputOffset;
2954 uint32_t InitialLength = Data.getU32(&InputOffset);
2955 if (InitialLength == 0xFFFFFFFF)
2956 return reportWarning("Dwarf64 bits no supported");
2957
2958 uint32_t CIEId = Data.getU32(&InputOffset);
2959 if (CIEId == 0xFFFFFFFF) {
2960 // This is a CIE, store it.
2961 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2962 LocalCIES[EntryOffset] = CIEData;
2963 // The -4 is to account for the CIEId we just read.
2964 InputOffset += InitialLength - 4;
2965 continue;
2966 }
2967
2968 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2969
2970 // Some compilers seem to emit frame info that doesn't start at
2971 // the function entry point, thus we can't just lookup the address
2972 // in the debug map. Use the linker's range map to see if the FDE
2973 // describes something that we can relocate.
2974 auto Range = Ranges.upper_bound(Loc);
2975 if (Range != Ranges.begin())
2976 --Range;
2977 if (Range == Ranges.end() || Range->first > Loc ||
2978 Range->second.first <= Loc) {
2979 // The +4 is to account for the size of the InitialLength field itself.
2980 InputOffset = EntryOffset + InitialLength + 4;
2981 continue;
2982 }
2983
2984 // This is an FDE, and we have a mapping.
2985 // Have we already emitted a corresponding CIE?
2986 StringRef CIEData = LocalCIES[CIEId];
2987 if (CIEData.empty())
2988 return reportWarning("Inconsistent debug_frame content. Dropping.");
2989
2990 // Look if we already emitted a CIE that corresponds to the
2991 // referenced one (the CIE data is the key of that lookup).
2992 auto IteratorInserted = EmittedCIEs.insert(
2993 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2994 // If there is no CIE yet for this ID, emit it.
2995 if (IteratorInserted.second ||
2996 // FIXME: dsymutil-classic only caches the last used CIE for
2997 // reuse. Mimic that behavior for now. Just removing that
2998 // second half of the condition and the LastCIEOffset variable
2999 // makes the code DTRT.
3000 LastCIEOffset != IteratorInserted.first->getValue()) {
3001 LastCIEOffset = Streamer->getFrameSectionSize();
3002 IteratorInserted.first->getValue() = LastCIEOffset;
3003 Streamer->emitCIE(CIEData);
3004 }
3005
3006 // Emit the FDE with updated address and CIE pointer.
3007 // (4 + AddrSize) is the size of the CIEId + initial_location
3008 // fields that will get reconstructed by emitFDE().
3009 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3010 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3011 Loc + Range->second.second,
3012 FrameData.substr(InputOffset, FDERemainingBytes));
3013 InputOffset += FDERemainingBytes;
3014 }
3015}
3016
Frederic Risseb85c8f2015-07-24 06:41:11 +00003017ErrorOr<const object::ObjectFile &>
3018DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3019 const DebugMap &Map) {
3020 auto ErrOrObjs =
3021 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
3022 if (std::error_code EC = ErrOrObjs.getError())
3023 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3024 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3025 if (std::error_code EC = ErrOrObj.getError())
3026 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3027 return ErrOrObj;
3028}
3029
Frederic Rissd3455182015-01-28 18:27:01 +00003030bool DwarfLinker::link(const DebugMap &Map) {
3031
3032 if (Map.begin() == Map.end()) {
3033 errs() << "Empty debug map.\n";
3034 return false;
3035 }
3036
Frederic Rissc99ea202015-02-28 00:29:11 +00003037 if (!createStreamer(Map.getTriple(), OutputFilename))
3038 return false;
3039
Frederic Rissb8b43d52015-03-04 22:07:44 +00003040 // Size of the DIEs (and headers) generated for the linked output.
3041 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003042 // A unique ID that identifies each compile unit.
3043 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00003044 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003045 CurrentDebugObject = Obj.get();
3046
Frederic Rissb9818322015-02-28 00:29:07 +00003047 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003048 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003049 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3050 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003051 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003052
Frederic Riss1036e642015-02-13 23:18:22 +00003053 // Look for relocations that correspond to debug map entries.
3054 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003055 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003056 outs() << "No valid relocations found. Skipping.\n";
3057 continue;
3058 }
3059
Frederic Riss563cba62015-01-28 22:15:14 +00003060 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003061 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003062 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003063
Frederic Riss563cba62015-01-28 22:15:14 +00003064 // In a first phase, just read in the debug info and store the DIE
3065 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00003066 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003067 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003068 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003069 outs() << "Input compilation unit:";
3070 CUDie->dump(outs(), CU.get(), 0);
3071 }
Frederic Riss1c650942015-07-21 22:41:43 +00003072 Units.emplace_back(*CU, UnitID++, !Options.NoODR);
3073 gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
3074 StringPool, ODRContexts);
Frederic Rissd3455182015-01-28 18:27:01 +00003075 }
Frederic Riss563cba62015-01-28 22:15:14 +00003076
Frederic Riss84c09a52015-02-13 23:18:34 +00003077 // Then mark all the DIEs that need to be present in the linked
3078 // output and collect some information about them. Note that this
3079 // loop can not be merged with the previous one becaue cross-cu
3080 // references require the ParentIdx to be setup for every CU in
3081 // the object file before calling this.
3082 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003083 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00003084 CurrentUnit, 0);
3085
Frederic Riss23e20e92015-03-07 01:25:09 +00003086 // The calls to applyValidRelocs inside cloneDIE will walk the
3087 // reloc array again (in the same way findValidRelocsInDebugInfo()
3088 // did). We need to reset the NextValidReloc index to the beginning.
3089 NextValidReloc = 0;
3090
Frederic Rissb8b43d52015-03-04 22:07:44 +00003091 // Construct the output DIE tree by cloning the DIEs we chose to
3092 // keep above. If there are no valid relocs, then there's nothing
3093 // to clone/emit.
3094 if (!ValidRelocs.empty())
3095 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003096 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00003097 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00003098 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
3099 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00003100 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00003101 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00003102 if (Options.NoOutput)
3103 continue;
3104 // FIXME: for compatibility with the classic dsymutil, we emit
3105 // an empty line table for the unit, even if the unit doesn't
3106 // actually exist in the DIE tree.
3107 patchLineTableForUnit(CurrentUnit, DwarfContext);
3108 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00003109 continue;
3110 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00003111 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00003112 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00003113 }
3114
3115 // Emit all the compile unit's debug information.
3116 if (!ValidRelocs.empty() && !Options.NoOutput)
3117 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00003118 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00003119 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00003120 Streamer->emitCompileUnitHeader(CurrentUnit);
3121 if (!CurrentUnit.getOutputUnitDIE())
3122 continue;
3123 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3124 }
3125
Frederic Riss5a642072015-06-05 23:06:11 +00003126 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
3127 patchFrameInfoForObject(*Obj, DwarfContext,
3128 Units[0].getOrigUnit().getAddressByteSize());
3129
Frederic Riss563cba62015-01-28 22:15:14 +00003130 // Clean-up before starting working on the next object.
3131 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003132 }
3133
Frederic Rissb8b43d52015-03-04 22:07:44 +00003134 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003135 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003136 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003137 Streamer->emitStrings(StringPool);
3138 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003139
Frederic Rissc99ea202015-02-28 00:29:11 +00003140 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00003141}
3142}
Frederic Rissd3455182015-01-28 18:27:01 +00003143
Frederic Rissb9818322015-02-28 00:29:07 +00003144bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3145 const LinkOptions &Options) {
3146 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003147 return Linker.link(DM);
3148}
3149}
Frederic Riss231f7142014-12-12 17:31:24 +00003150}