blob: ed06dba8ab3147e12c5ab23b756ae83bb24818b4 [file] [log] [blame]
Frederic Riss231f7142014-12-12 17:31:24 +00001//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "DebugMap.h"
Frederic Rissd3455182015-01-28 18:27:01 +000010#include "BinaryHolder.h"
11#include "DebugMap.h"
Frederic Riss231f7142014-12-12 17:31:24 +000012#include "dsymutil.h"
Frederic Riss30711fb2015-08-26 05:09:52 +000013#include "NonRelocatableStringpool.h"
Frederic Riss1af75f72015-03-12 18:45:10 +000014#include "llvm/ADT/IntervalMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000015#include "llvm/ADT/StringMap.h"
16#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000017#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000018#include "llvm/CodeGen/DIE.h"
Frederic Riss1c650942015-07-21 22:41:43 +000019#include "llvm/Config/config.h"
Zachary Turner82af9432015-01-30 18:07:45 +000020#include "llvm/DebugInfo/DWARF/DWARFContext.h"
21#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000022#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000023#include "llvm/MC/MCAsmBackend.h"
24#include "llvm/MC/MCAsmInfo.h"
25#include "llvm/MC/MCContext.h"
26#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000027#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000028#include "llvm/MC/MCInstrInfo.h"
29#include "llvm/MC/MCObjectFileInfo.h"
30#include "llvm/MC/MCRegisterInfo.h"
31#include "llvm/MC/MCStreamer.h"
Pete Cooper81902a32015-05-15 22:19:42 +000032#include "llvm/MC/MCSubtargetInfo.h"
Frederic Riss1036e642015-02-13 23:18:22 +000033#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000034#include "llvm/Support/Dwarf.h"
35#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000036#include "llvm/Support/TargetRegistry.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000039#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000040#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000041
42namespace llvm {
43namespace dsymutil {
44
Frederic Rissd3455182015-01-28 18:27:01 +000045namespace {
46
Frederic Riss1af75f72015-03-12 18:45:10 +000047template <typename KeyT, typename ValT>
48using HalfOpenIntervalMap =
49 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
50 IntervalMapHalfOpenInfo<KeyT>>;
51
Frederic Riss25440872015-03-13 23:30:31 +000052typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
53
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000054// FIXME: Delete this structure.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000055struct PatchLocation {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000056 DIE::value_iterator I;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000057
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000058 PatchLocation() = default;
59 PatchLocation(DIE::value_iterator I) : I(I) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000060
61 void set(uint64_t New) const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000062 assert(I);
63 const auto &Old = *I;
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000064 assert(Old.getType() == DIEValue::isInteger);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000065 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000066 }
67
68 uint64_t get() const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000069 assert(I);
70 return I->getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000071 }
72};
73
Frederic Riss1c650942015-07-21 22:41:43 +000074class CompileUnit;
75struct DeclMapInfo;
Frederic Riss1c650942015-07-21 22:41:43 +000076
77/// A DeclContext is a named program scope that is used for ODR
78/// uniquing of types.
79/// The set of DeclContext for the ODR-subject parts of a Dwarf link
80/// is expanded (and uniqued) with each new object file processed. We
81/// need to determine the context of each DIE in an linked object file
82/// to see if the corresponding type has already been emitted.
83///
84/// The contexts are conceptually organised as a tree (eg. a function
85/// scope is contained in a namespace scope that contains other
86/// scopes), but storing/accessing them in an actual tree is too
87/// inefficient: we need to be able to very quickly query a context
88/// for a given child context by name. Storing a StringMap in each
89/// DeclContext would be too space inefficient.
90/// The solution here is to give each DeclContext a link to its parent
91/// (this allows to walk up the tree), but to query the existance of a
92/// specific DeclContext using a separate DenseMap keyed on the hash
93/// of the fully qualified name of the context.
94class DeclContext {
95 unsigned QualifiedNameHash;
96 uint32_t Line;
97 uint32_t ByteSize;
98 uint16_t Tag;
99 StringRef Name;
100 StringRef File;
101 const DeclContext &Parent;
102 const DWARFDebugInfoEntryMinimal *LastSeenDIE;
103 uint32_t LastSeenCompileUnitID;
104 uint32_t CanonicalDIEOffset;
105
106 friend DeclMapInfo;
107
108public:
109 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
110
111 DeclContext()
112 : QualifiedNameHash(0), Line(0), ByteSize(0),
113 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
114 LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
115
116 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
117 StringRef Name, StringRef File, const DeclContext &Parent,
118 const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
119 unsigned CUId = 0)
120 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
121 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
122 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
123
124 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
125
126 bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
127
128 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
129 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
130
131 uint16_t getTag() const { return Tag; }
132 StringRef getName() const { return Name; }
133};
134
135/// Info type for the DenseMap storing the DeclContext pointers.
136struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
137 using DenseMapInfo<DeclContext *>::getEmptyKey;
138 using DenseMapInfo<DeclContext *>::getTombstoneKey;
139
140 static unsigned getHashValue(const DeclContext *Ctxt) {
141 return Ctxt->QualifiedNameHash;
142 }
143
144 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
145 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
146 return RHS == LHS;
147 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
148 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
149 LHS->Name.data() == RHS->Name.data() &&
150 LHS->File.data() == RHS->File.data() &&
151 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
152 }
153};
154
155/// This class gives a tree-like API to the DenseMap that stores the
156/// DeclContext objects. It also holds the BumpPtrAllocator where
157/// these objects will be allocated.
158class DeclContextTree {
159 BumpPtrAllocator Allocator;
160 DeclContext Root;
161 DeclContext::Map Contexts;
162
163public:
164 /// Get the child of \a Context described by \a DIE in \a Unit. The
165 /// required strings will be interned in \a StringPool.
166 /// \returns The child DeclContext along with one bit that is set if
167 /// this context is invalid.
168 /// FIXME: the invalid bit along the return value is to emulate some
169 /// dsymutil-classic functionality. See the fucntion definition for
170 /// a more thorough discussion of its use.
171 PointerIntPair<DeclContext *, 1>
172 getChildDeclContext(DeclContext &Context,
173 const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
174 NonRelocatableStringpool &StringPool);
175
176 DeclContext &getRoot() { return Root; }
177};
178
Frederic Riss563cba62015-01-28 22:15:14 +0000179/// \brief Stores all information relating to a compile unit, be it in
180/// its original instance in the object file to its brand new cloned
181/// and linked DIE tree.
182class CompileUnit {
183public:
184 /// \brief Information gathered about a DIE in the object file.
185 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +0000186 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss1c650942015-07-21 22:41:43 +0000187 DeclContext *Ctxt; ///< ODR Declaration context.
Frederic Riss9833de62015-03-06 23:22:53 +0000188 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +0000189 uint32_t ParentIdx; ///< The index of this DIE's parent.
190 bool Keep; ///< Is the DIE part of the linked output?
191 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +0000192 };
193
Frederic Riss1c650942015-07-21 22:41:43 +0000194 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR)
Frederic Riss3cced052015-03-14 03:46:40 +0000195 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000196 Ranges(RangeAlloc) {
Frederic Riss563cba62015-01-28 22:15:14 +0000197 Info.resize(OrigUnit.getNumDIEs());
Frederic Riss1c650942015-07-21 22:41:43 +0000198
199 const auto *CUDie = OrigUnit.getUnitDIE(false);
200 unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
201 &OrigUnit, dwarf::DW_AT_language, 0);
202 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
203 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
204 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
205 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
206 Lang == dwarf::DW_LANG_ObjC_plus_plus);
Frederic Riss563cba62015-01-28 22:15:14 +0000207 }
208
Frederic Riss2838f9e2015-03-05 05:29:05 +0000209 CompileUnit(CompileUnit &&RHS)
210 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
211 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000212 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
213 // The CompileUnit container has been 'reserve()'d with the right
214 // size. We cannot move the IntervalMap anyway.
215 llvm_unreachable("CompileUnits should not be moved.");
216 }
David Blaikiea8adc132015-03-04 22:20:52 +0000217
Frederic Rissc3349d42015-02-13 23:18:27 +0000218 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000219
Frederic Riss3cced052015-03-14 03:46:40 +0000220 unsigned getUniqueID() const { return ID; }
221
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +0000222 DIE *getOutputUnitDIE() const { return CUDie; }
223 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000224
Frederic Riss1c650942015-07-21 22:41:43 +0000225 bool hasODR() const { return HasODR; }
226
Frederic Riss563cba62015-01-28 22:15:14 +0000227 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
228 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
229
Frederic Rissb8b43d52015-03-04 22:07:44 +0000230 uint64_t getStartOffset() const { return StartOffset; }
231 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000232 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000233
Frederic Riss5a62dc32015-03-13 18:35:54 +0000234 uint64_t getLowPc() const { return LowPc; }
235 uint64_t getHighPc() const { return HighPc; }
236
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000237 Optional<PatchLocation> getUnitRangesAttribute() const {
238 return UnitRangeAttribute;
239 }
Frederic Riss25440872015-03-13 23:30:31 +0000240 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000241 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000242 return RangeAttributes;
243 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000244
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000245 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000246 getLocationAttributes() const {
247 return LocationAttributes;
248 }
249
Frederic Riss9d441b62015-03-06 23:22:50 +0000250 /// \brief Compute the end offset for this unit. Must be
251 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000252 /// \returns the next unit offset (which is also the current
253 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000254 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000255
Frederic Riss6afcfce2015-03-13 18:35:57 +0000256 /// \brief Keep track of a forward reference to DIE \p Die in \p
257 /// RefUnit by \p Attr. The attribute should be fixed up later to
Frederic Riss1c650942015-07-21 22:41:43 +0000258 /// point to the absolute offset of \p Die in the debug_info section
259 /// or to the canonical offset of \p Ctxt if it is non-null.
Frederic Riss6afcfce2015-03-13 18:35:57 +0000260 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000261 DeclContext *Ctxt, PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000262
263 /// \brief Apply all fixups recored by noteForwardReference().
264 void fixupForwardReferences();
265
Frederic Riss1af75f72015-03-12 18:45:10 +0000266 /// \brief Add a function range [\p LowPC, \p HighPC) that is
267 /// relocatad by applying offset \p PCOffset.
268 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
269
Frederic Riss5c9c7062015-03-13 23:55:29 +0000270 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000271 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000272 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000273
Frederic Rissdfb97902015-03-14 15:49:07 +0000274 /// \brief Keep track of a location attribute pointing to a location
275 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000276 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000277
Frederic Rissbce93ff2015-03-16 02:05:10 +0000278 /// \brief Add a name accelerator entry for \p Die with \p Name
279 /// which is stored in the string table at \p Offset.
280 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
281 bool SkipPubnamesSection = false);
282
283 /// \brief Add a type accelerator entry for \p Die with \p Name
284 /// which is stored in the string table at \p Offset.
285 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
286
287 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000288 StringRef Name; ///< Name of the entry.
289 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000290 uint32_t NameOffset; ///< Offset of Name in the string pool.
291 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
292
293 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
294 bool SkipPubSection = false)
295 : Name(Name), Die(Die), NameOffset(NameOffset),
296 SkipPubSection(SkipPubSection) {}
297 };
298
299 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
300 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
301
Frederic Riss1c650942015-07-21 22:41:43 +0000302 /// Get the full path for file \a FileNum in the line table
303 const char *getResolvedPath(unsigned FileNum) {
304 if (FileNum >= ResolvedPaths.size())
305 return nullptr;
306 return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
307 : nullptr;
308 }
309
310 /// Set the fully resolved path for the line-table's file \a FileNum
311 /// to \a Path.
312 void setResolvedPath(unsigned FileNum, const std::string &Path) {
313 if (ResolvedPaths.size() <= FileNum)
314 ResolvedPaths.resize(FileNum + 1);
315 ResolvedPaths[FileNum] = Path;
316 }
317
Frederic Riss563cba62015-01-28 22:15:14 +0000318private:
319 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000320 unsigned ID;
Frederic Riss1c650942015-07-21 22:41:43 +0000321 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
322 DIE *CUDie; ///< Root of the linked DIE tree.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000323
324 uint64_t StartOffset;
325 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000326
Frederic Riss5a62dc32015-03-13 18:35:54 +0000327 uint64_t LowPc;
328 uint64_t HighPc;
329
Frederic Riss9833de62015-03-06 23:22:53 +0000330 /// \brief A list of attributes to fixup with the absolute offset of
331 /// a DIE in the debug_info section.
332 ///
333 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000334 /// cloning because for cross-cu forward refences the target DIE's
335 /// offset isn't known you emit the reference attribute.
Frederic Riss1c650942015-07-21 22:41:43 +0000336 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
337 PatchLocation>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000338
Frederic Riss25440872015-03-13 23:30:31 +0000339 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000340 /// \brief The ranges in that interval map are the PC ranges for
341 /// functions in this unit, associated with the PC offset to apply
342 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000343 FunctionIntervals Ranges;
344
345 /// \brief DW_AT_ranges attributes to patch after we have gathered
346 /// all the unit's function addresses.
347 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000348 std::vector<PatchLocation> RangeAttributes;
349 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000350 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000351
352 /// \brief Location attributes that need to be transfered from th
353 /// original debug_loc section to the liked one. They are stored
354 /// along with the PC offset that is to be applied to their
355 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000356 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000357
358 /// \brief Accelerator entries for the unit, both for the pub*
359 /// sections and the apple* ones.
360 /// @{
361 std::vector<AccelInfo> Pubnames;
362 std::vector<AccelInfo> Pubtypes;
363 /// @}
Frederic Riss1c650942015-07-21 22:41:43 +0000364
365 /// Cached resolved paths from the line table.
366 std::vector<std::string> ResolvedPaths;
367
368 /// Is this unit subject to the ODR rule?
369 bool HasODR;
Frederic Riss563cba62015-01-28 22:15:14 +0000370};
371
Frederic Riss9d441b62015-03-06 23:22:50 +0000372uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000373 NextUnitOffset = StartOffset + 11 /* Header size */;
374 // The root DIE might be null, meaning that the Unit had nothing to
375 // contribute to the linked output. In that case, we will emit the
376 // unit header without any actual DIE.
377 if (CUDie)
378 NextUnitOffset += CUDie->getSize();
379 return NextUnitOffset;
380}
381
Frederic Riss6afcfce2015-03-13 18:35:57 +0000382/// \brief Keep track of a forward cross-cu reference from this unit
383/// to \p Die that lives in \p RefUnit.
384void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000385 DeclContext *Ctxt, PatchLocation Attr) {
386 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000387}
388
389/// \brief Apply all fixups recorded by noteForwardReference().
390void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000391 for (const auto &Ref : ForwardDIEReferences) {
392 DIE *RefDie;
393 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000394 PatchLocation Attr;
Frederic Riss1c650942015-07-21 22:41:43 +0000395 DeclContext *Ctxt;
396 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
397 if (Ctxt && Ctxt->getCanonicalDIEOffset())
398 Attr.set(Ctxt->getCanonicalDIEOffset());
399 else
400 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000401 }
Frederic Riss9833de62015-03-06 23:22:53 +0000402}
403
Frederic Riss5a62dc32015-03-13 18:35:54 +0000404void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
405 int64_t PcOffset) {
406 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
407 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
408 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000409}
410
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000411void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000412 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
413 RangeAttributes.push_back(Attr);
414 else
415 UnitRangeAttribute = Attr;
416}
417
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000418void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000419 LocationAttributes.emplace_back(Attr, PcOffset);
420}
421
Frederic Rissbce93ff2015-03-16 02:05:10 +0000422/// \brief Add a name accelerator entry for \p Die with \p Name
423/// which is stored in the string table at \p Offset.
424void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
425 uint32_t Offset, bool SkipPubSection) {
426 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
427}
428
429/// \brief Add a type accelerator entry for \p Die with \p Name
430/// which is stored in the string table at \p Offset.
431void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
432 uint32_t Offset) {
433 Pubtypes.emplace_back(Name, Die, Offset, false);
434}
435
Frederic Rissc99ea202015-02-28 00:29:11 +0000436/// \brief The Dwarf streaming logic
437///
438/// All interactions with the MC layer that is used to build the debug
439/// information binary representation are handled in this class.
440class DwarfStreamer {
441 /// \defgroup MCObjects MC layer objects constructed by the streamer
442 /// @{
443 std::unique_ptr<MCRegisterInfo> MRI;
444 std::unique_ptr<MCAsmInfo> MAI;
445 std::unique_ptr<MCObjectFileInfo> MOFI;
446 std::unique_ptr<MCContext> MC;
447 MCAsmBackend *MAB; // Owned by MCStreamer
448 std::unique_ptr<MCInstrInfo> MII;
449 std::unique_ptr<MCSubtargetInfo> MSTI;
450 MCCodeEmitter *MCE; // Owned by MCStreamer
451 MCStreamer *MS; // Owned by AsmPrinter
452 std::unique_ptr<TargetMachine> TM;
453 std::unique_ptr<AsmPrinter> Asm;
454 /// @}
455
456 /// \brief the file we stream the linked Dwarf to.
457 std::unique_ptr<raw_fd_ostream> OutFile;
458
Frederic Riss25440872015-03-13 23:30:31 +0000459 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000460 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000461 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000462 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000463
Frederic Rissbce93ff2015-03-16 02:05:10 +0000464 /// \brief Emit the pubnames or pubtypes section contribution for \p
465 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000466 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000467 const CompileUnit &Unit,
468 const std::vector<CompileUnit::AccelInfo> &Names);
469
Frederic Rissc99ea202015-02-28 00:29:11 +0000470public:
471 /// \brief Actually create the streamer and the ouptut file.
472 ///
473 /// This could be done directly in the constructor, but it feels
474 /// more natural to handle errors through return value.
475 bool init(Triple TheTriple, StringRef OutputFilename);
476
Frederic Rissb8b43d52015-03-04 22:07:44 +0000477 /// \brief Dump the file to the disk.
Frederic Riss5f369032015-08-26 06:41:57 +0000478 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000479
480 AsmPrinter &getAsmPrinter() const { return *Asm; }
481
482 /// \brief Set the current output section to debug_info and change
483 /// the MC Dwarf version to \p DwarfVersion.
484 void switchToDebugInfoSection(unsigned DwarfVersion);
485
486 /// \brief Emit the compilation unit header for \p Unit in the
487 /// debug_info section.
488 ///
489 /// As a side effect, this also switches the current Dwarf version
490 /// of the MC layer to the one of U.getOrigUnit().
491 void emitCompileUnitHeader(CompileUnit &Unit);
492
493 /// \brief Recursively emit the DIE tree rooted at \p Die.
494 void emitDIE(DIE &Die);
495
496 /// \brief Emit the abbreviation table \p Abbrevs to the
497 /// debug_abbrev section.
498 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000499
500 /// \brief Emit the string table described by \p Pool.
501 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000502
503 /// \brief Emit debug_ranges for \p FuncRange by translating the
504 /// original \p Entries.
505 void emitRangesEntries(
506 int64_t UnitPcOffset, uint64_t OrigLowPc,
507 FunctionIntervals::const_iterator FuncRange,
508 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
509 unsigned AddressSize);
510
Frederic Riss563b1b02015-03-14 03:46:51 +0000511 /// \brief Emit debug_aranges entries for \p Unit and if \p
512 /// DoRangesSection is true, also emit the debug_ranges entries for
513 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
514 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000515
516 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000517
518 /// \brief Emit the debug_loc contribution for \p Unit by copying
519 /// the entries from \p Dwarf and offseting them. Update the
520 /// location attributes to point to the new entries.
521 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000522
523 /// \brief Emit the line table described in \p Rows into the
524 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000525 void emitLineTableForUnit(MCDwarfLineTableParams Params,
526 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000527 std::vector<DWARFDebugLine::Row> &Rows,
528 unsigned AdddressSize);
529
530 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000531
532 /// \brief Emit the .debug_pubnames contribution for \p Unit.
533 void emitPubNamesForUnit(const CompileUnit &Unit);
534
535 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
536 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000537
538 /// \brief Emit a CIE.
539 void emitCIE(StringRef CIEBytes);
540
541 /// \brief Emit an FDE with data \p Bytes.
542 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
543 StringRef Bytes);
544
545 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000546};
547
548bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
549 std::string ErrorStr;
550 std::string TripleName;
551 StringRef Context = "dwarf streamer init";
552
553 // Get the target.
554 const Target *TheTarget =
555 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
556 if (!TheTarget)
557 return error(ErrorStr, Context);
558 TripleName = TheTriple.getTriple();
559
560 // Create all the MC Objects.
561 MRI.reset(TheTarget->createMCRegInfo(TripleName));
562 if (!MRI)
563 return error(Twine("no register info for target ") + TripleName, Context);
564
565 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
566 if (!MAI)
567 return error("no asm info for target " + TripleName, Context);
568
569 MOFI.reset(new MCObjectFileInfo);
570 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000571 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
Frederic Rissc99ea202015-02-28 00:29:11 +0000572 *MC);
573
574 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
575 if (!MAB)
576 return error("no asm backend for target " + TripleName, Context);
577
578 MII.reset(TheTarget->createMCInstrInfo());
579 if (!MII)
580 return error("no instr info info for target " + TripleName, Context);
581
582 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
583 if (!MSTI)
584 return error("no subtarget info for target " + TripleName, Context);
585
Eric Christopher0169e422015-03-10 22:03:14 +0000586 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000587 if (!MCE)
588 return error("no code emitter for target " + TripleName, Context);
589
590 // Create the output file.
591 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000592 OutFile =
593 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000594 if (EC)
595 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
596
Rafael Espindolaf696df12015-03-16 22:29:29 +0000597 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000598 *MSTI, false,
599 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000600 if (!MS)
601 return error("no object streamer for target " + TripleName, Context);
602
603 // Finally create the AsmPrinter we'll use to emit the DIEs.
604 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
605 if (!TM)
606 return error("no target machine for target " + TripleName, Context);
607
608 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
609 if (!Asm)
610 return error("no asm printer for target " + TripleName, Context);
611
Frederic Riss25440872015-03-13 23:30:31 +0000612 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000613 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000614 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000615 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000616
Frederic Rissc99ea202015-02-28 00:29:11 +0000617 return true;
618}
619
Frederic Riss5f369032015-08-26 06:41:57 +0000620bool DwarfStreamer::finish() {
Frederic Rissc99ea202015-02-28 00:29:11 +0000621 MS->Finish();
622 return true;
623}
624
Frederic Rissb8b43d52015-03-04 22:07:44 +0000625/// \brief Set the current output section to debug_info and change
626/// the MC Dwarf version to \p DwarfVersion.
627void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
628 MS->SwitchSection(MOFI->getDwarfInfoSection());
629 MC->setDwarfVersion(DwarfVersion);
630}
631
632/// \brief Emit the compilation unit header for \p Unit in the
633/// debug_info section.
634///
635/// A Dwarf scetion header is encoded as:
636/// uint32_t Unit length (omiting this field)
637/// uint16_t Version
638/// uint32_t Abbreviation table offset
639/// uint8_t Address size
640///
641/// Leading to a total of 11 bytes.
642void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
643 unsigned Version = Unit.getOrigUnit().getVersion();
644 switchToDebugInfoSection(Version);
645
646 // Emit size of content not including length itself. The size has
647 // already been computed in CompileUnit::computeOffsets(). Substract
648 // 4 to that size to account for the length field.
649 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
650 Asm->EmitInt16(Version);
651 // We share one abbreviations table across all units so it's always at the
652 // start of the section.
653 Asm->EmitInt32(0);
654 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
655}
656
657/// \brief Emit the \p Abbrevs array as the shared abbreviation table
658/// for the linked Dwarf file.
659void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
660 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
661 Asm->emitDwarfAbbrevs(Abbrevs);
662}
663
664/// \brief Recursively emit the DIE tree rooted at \p Die.
665void DwarfStreamer::emitDIE(DIE &Die) {
666 MS->SwitchSection(MOFI->getDwarfInfoSection());
667 Asm->emitDwarfDIE(Die);
668}
669
Frederic Rissef648462015-03-06 17:56:30 +0000670/// \brief Emit the debug_str section stored in \p Pool.
671void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000672 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000673 for (auto *Entry = Pool.getFirstEntry(); Entry;
674 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000675 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000676 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
677}
678
Frederic Riss25440872015-03-13 23:30:31 +0000679/// \brief Emit the debug_range section contents for \p FuncRange by
680/// translating the original \p Entries. The debug_range section
681/// format is totally trivial, consisting just of pairs of address
682/// sized addresses describing the ranges.
683void DwarfStreamer::emitRangesEntries(
684 int64_t UnitPcOffset, uint64_t OrigLowPc,
685 FunctionIntervals::const_iterator FuncRange,
686 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
687 unsigned AddressSize) {
688 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
689
690 // Offset each range by the right amount.
Frederic Riss94546202015-08-31 05:09:32 +0000691 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
Frederic Riss25440872015-03-13 23:30:31 +0000692 for (const auto &Range : Entries) {
693 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
694 warn("unsupported base address selection operation",
695 "emitting debug_ranges");
696 break;
697 }
698 // Do not emit empty ranges.
699 if (Range.StartAddress == Range.EndAddress)
700 continue;
701
702 // All range entries should lie in the function range.
703 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
704 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
705 warn("inconsistent range data.", "emitting debug_ranges");
706 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
707 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
708 RangesSectionSize += 2 * AddressSize;
709 }
710
711 // Add the terminator entry.
712 MS->EmitIntValue(0, AddressSize);
713 MS->EmitIntValue(0, AddressSize);
714 RangesSectionSize += 2 * AddressSize;
715}
716
Frederic Riss563b1b02015-03-14 03:46:51 +0000717/// \brief Emit the debug_aranges contribution of a unit and
718/// if \p DoDebugRanges is true the debug_range contents for a
719/// compile_unit level DW_AT_ranges attribute (Which are basically the
720/// same thing with a different base address).
721/// Just aggregate all the ranges gathered inside that unit.
722void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
723 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000724 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
725 // Gather the ranges in a vector, so that we can simplify them. The
726 // IntervalMap will have coalesced the non-linked ranges, but here
727 // we want to coalesce the linked addresses.
728 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
729 const auto &FunctionRanges = Unit.getFunctionRanges();
730 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
731 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000732 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
733 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000734
735 // The object addresses where sorted, but again, the linked
736 // addresses might end up in a different order.
737 std::sort(Ranges.begin(), Ranges.end());
738
Frederic Riss563b1b02015-03-14 03:46:51 +0000739 if (!Ranges.empty()) {
740 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
741
Rafael Espindola9ab09232015-03-17 20:07:06 +0000742 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
743 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000744
745 unsigned HeaderSize =
746 sizeof(int32_t) + // Size of contents (w/o this field
747 sizeof(int16_t) + // DWARF ARange version number
748 sizeof(int32_t) + // Offset of CU in the .debug_info section
749 sizeof(int8_t) + // Pointer Size (in bytes)
750 sizeof(int8_t); // Segment Size (in bytes)
751
752 unsigned TupleSize = AddressSize * 2;
753 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
754
755 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000756 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000757 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
758 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
759 Asm->EmitInt8(AddressSize); // Address size
760 Asm->EmitInt8(0); // Segment size
761
Lang Hames9ff69c82015-04-24 19:11:51 +0000762 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000763
764 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
765 ++Range) {
766 uint64_t RangeStart = Range->first;
767 MS->EmitIntValue(RangeStart, AddressSize);
768 while ((Range + 1) != End && Range->second == (Range + 1)->first)
769 ++Range;
770 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
771 }
772
773 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000774 Asm->OutStreamer->EmitIntValue(0, AddressSize);
775 Asm->OutStreamer->EmitIntValue(0, AddressSize);
776 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000777 }
778
779 if (!DoDebugRanges)
780 return;
781
782 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
783 // Offset each range by the right amount.
784 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000785 // Emit coalesced ranges.
786 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000787 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000788 while (Range + 1 != End && Range->second == (Range + 1)->first)
789 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000790 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000791 RangesSectionSize += 2 * AddressSize;
792 }
793
794 // Add the terminator entry.
795 MS->EmitIntValue(0, AddressSize);
796 MS->EmitIntValue(0, AddressSize);
797 RangesSectionSize += 2 * AddressSize;
798}
799
Frederic Rissdfb97902015-03-14 15:49:07 +0000800/// \brief Emit location lists for \p Unit and update attribtues to
801/// point to the new entries.
802void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
803 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000804 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000805
806 if (Attributes.empty())
807 return;
808
809 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
810
811 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
812 const DWARFSection &InputSec = Dwarf.getLocSection();
813 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
814 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000815 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000816 int64_t UnitPcOffset = 0;
817 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
818 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
819 if (OrigLowPc != -1ULL)
820 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
821
822 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000823 uint32_t Offset = Attr.first.get();
824 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000825 // This is the quantity to add to the old location address to get
826 // the correct address for the new one.
827 int64_t LocPcOffset = Attr.second + UnitPcOffset;
828 while (Data.isValidOffset(Offset)) {
829 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
830 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
831 LocSectionSize += 2 * AddressSize;
832 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000833 Asm->OutStreamer->EmitIntValue(0, AddressSize);
834 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000835 break;
836 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000837 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
838 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000839 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000840 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000841 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000842 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000843 StringRef(InputSec.Data.substr(Offset, Length)));
844 Offset += Length;
845 LocSectionSize += Length + 2;
846 }
847 }
848}
849
Frederic Rissa5e14532015-08-07 15:14:13 +0000850void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
851 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000852 unsigned MinInstLength,
853 std::vector<DWARFDebugLine::Row> &Rows,
854 unsigned PointerSize) {
855 // Switch to the section where the table will be emitted into.
856 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000857 MCSymbol *LineStartSym = MC->createTempSymbol();
858 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000859
860 // The first 4 bytes is the total length of the information for this
861 // compilation unit (not including these 4 bytes for the length).
862 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000863 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000864 // Copy Prologue.
865 MS->EmitBytes(PrologueBytes);
866 LineSectionSize += PrologueBytes.size() + 4;
867
Frederic Rissc3820d02015-03-15 22:20:28 +0000868 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000869 raw_svector_ostream EncodingOS(EncodingBuffer);
870
871 if (Rows.empty()) {
872 // We only have the dummy entry, dsymutil emits an entry with a 0
873 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000874 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000875 MS->EmitBytes(EncodingOS.str());
876 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000877 MS->EmitLabel(LineEndSym);
878 return;
879 }
880
881 // Line table state machine fields
882 unsigned FileNum = 1;
883 unsigned LastLine = 1;
884 unsigned Column = 0;
885 unsigned IsStatement = 1;
886 unsigned Isa = 0;
887 uint64_t Address = -1ULL;
888
889 unsigned RowsSinceLastSequence = 0;
890
891 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
892 auto &Row = Rows[Idx];
893
894 int64_t AddressDelta;
895 if (Address == -1ULL) {
896 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
897 MS->EmitULEB128IntValue(PointerSize + 1);
898 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
899 MS->EmitIntValue(Row.Address, PointerSize);
900 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
901 AddressDelta = 0;
902 } else {
903 AddressDelta = (Row.Address - Address) / MinInstLength;
904 }
905
906 // FIXME: code copied and transfromed from
907 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
908 // this code, but the current compatibility requirement with
909 // classic dsymutil makes it hard. Revisit that once this
910 // requirement is dropped.
911
912 if (FileNum != Row.File) {
913 FileNum = Row.File;
914 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
915 MS->EmitULEB128IntValue(FileNum);
916 LineSectionSize += 1 + getULEB128Size(FileNum);
917 }
918 if (Column != Row.Column) {
919 Column = Row.Column;
920 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
921 MS->EmitULEB128IntValue(Column);
922 LineSectionSize += 1 + getULEB128Size(Column);
923 }
924
925 // FIXME: We should handle the discriminator here, but dsymutil
926 // doesn' consider it, thus ignore it for now.
927
928 if (Isa != Row.Isa) {
929 Isa = Row.Isa;
930 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
931 MS->EmitULEB128IntValue(Isa);
932 LineSectionSize += 1 + getULEB128Size(Isa);
933 }
934 if (IsStatement != Row.IsStmt) {
935 IsStatement = Row.IsStmt;
936 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
937 LineSectionSize += 1;
938 }
939 if (Row.BasicBlock) {
940 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
941 LineSectionSize += 1;
942 }
943
944 if (Row.PrologueEnd) {
945 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
946 LineSectionSize += 1;
947 }
948
949 if (Row.EpilogueBegin) {
950 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
951 LineSectionSize += 1;
952 }
953
954 int64_t LineDelta = int64_t(Row.Line) - LastLine;
955 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000956 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000957 MS->EmitBytes(EncodingOS.str());
958 LineSectionSize += EncodingBuffer.size();
959 EncodingBuffer.resize(0);
960 Address = Row.Address;
961 LastLine = Row.Line;
962 RowsSinceLastSequence++;
963 } else {
964 if (LineDelta) {
965 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
966 MS->EmitSLEB128IntValue(LineDelta);
967 LineSectionSize += 1 + getSLEB128Size(LineDelta);
968 }
969 if (AddressDelta) {
970 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
971 MS->EmitULEB128IntValue(AddressDelta);
972 LineSectionSize += 1 + getULEB128Size(AddressDelta);
973 }
Frederic Rissa5e14532015-08-07 15:14:13 +0000974 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000975 MS->EmitBytes(EncodingOS.str());
976 LineSectionSize += EncodingBuffer.size();
977 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +0000978 Address = -1ULL;
979 LastLine = FileNum = IsStatement = 1;
980 RowsSinceLastSequence = Column = Isa = 0;
981 }
982 }
983
984 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000985 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000986 MS->EmitBytes(EncodingOS.str());
987 LineSectionSize += EncodingBuffer.size();
988 EncodingBuffer.resize(0);
989 }
990
991 MS->EmitLabel(LineEndSym);
992}
993
Frederic Rissbce93ff2015-03-16 02:05:10 +0000994/// \brief Emit the pubnames or pubtypes section contribution for \p
995/// Unit into \p Sec. The data is provided in \p Names.
996void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000997 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000998 const std::vector<CompileUnit::AccelInfo> &Names) {
999 if (Names.empty())
1000 return;
1001
1002 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001003 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001004 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1005 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001006
1007 bool HeaderEmitted = false;
1008 // Emit the pubnames for this compilation unit.
1009 for (const auto &Name : Names) {
1010 if (Name.SkipPubSection)
1011 continue;
1012
1013 if (!HeaderEmitted) {
1014 // Emit the header.
1015 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001016 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001017 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001018 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001019 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1020 HeaderEmitted = true;
1021 }
1022 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001023 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001024 StringRef(Name.Name.data(), Name.Name.size() + 1));
1025 }
1026
1027 if (!HeaderEmitted)
1028 return;
1029 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001030 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001031}
1032
1033/// \brief Emit .debug_pubnames for \p Unit.
1034void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1035 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1036 "names", Unit, Unit.getPubnames());
1037}
1038
1039/// \brief Emit .debug_pubtypes for \p Unit.
1040void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1041 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1042 "types", Unit, Unit.getPubtypes());
1043}
1044
Frederic Riss5a642072015-06-05 23:06:11 +00001045/// \brief Emit a CIE into the debug_frame section.
1046void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1047 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1048
1049 MS->EmitBytes(CIEBytes);
1050 FrameSectionSize += CIEBytes.size();
1051}
1052
1053/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1054/// contains the FDE data without the length, CIE offset and address
1055/// which will be replaced with the paramter values.
1056void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1057 uint32_t Address, StringRef FDEBytes) {
1058 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1059
1060 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1061 MS->EmitIntValue(CIEOffset, 4);
1062 MS->EmitIntValue(Address, AddrSize);
1063 MS->EmitBytes(FDEBytes);
1064 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1065}
1066
Frederic Rissd3455182015-01-28 18:27:01 +00001067/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001068///
1069/// The link of the dwarf information from the object files will be
1070/// driven by the selection of 'root DIEs', which are DIEs that
1071/// describe variables or functions that are present in the linked
1072/// binary (and thus have entries in the debug map). All the debug
1073/// information that will be linked (the DIEs, but also the line
1074/// tables, ranges, ...) is derived from that set of root DIEs.
1075///
1076/// The root DIEs are identified because they contain relocations that
1077/// correspond to a debug map entry at specific places (the low_pc for
1078/// a function, the location for a variable). These relocations are
1079/// called ValidRelocs in the DwarfLinker and are gathered as a very
1080/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001081class DwarfLinker {
1082public:
Frederic Rissb9818322015-02-28 00:29:07 +00001083 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1084 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001085 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001086
Frederic Rissb8b43d52015-03-04 22:07:44 +00001087 ~DwarfLinker() {
1088 for (auto *Abbrev : Abbreviations)
1089 delete Abbrev;
1090 }
1091
Frederic Rissd3455182015-01-28 18:27:01 +00001092 /// \brief Link the contents of the DebugMap.
1093 bool link(const DebugMap &);
1094
1095private:
Frederic Riss563cba62015-01-28 22:15:14 +00001096 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001097 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001098
1099 /// \brief Called at the end of a debug object link.
1100 void endDebugObject();
1101
Frederic Riss1036e642015-02-13 23:18:22 +00001102 /// \defgroup FindValidRelocations Translate debug map into a list
1103 /// of relevant relocations
1104 ///
1105 /// @{
1106 struct ValidReloc {
1107 uint32_t Offset;
1108 uint32_t Size;
1109 uint64_t Addend;
1110 const DebugMapObject::DebugMapEntry *Mapping;
1111
1112 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1113 const DebugMapObject::DebugMapEntry *Mapping)
1114 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1115
1116 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1117 };
1118
1119 /// \brief The valid relocations for the current DebugMapObject.
1120 /// This vector is sorted by relocation offset.
1121 std::vector<ValidReloc> ValidRelocs;
1122
1123 /// \brief Index into ValidRelocs of the next relocation to
1124 /// consider. As we walk the DIEs in acsending file offset and as
1125 /// ValidRelocs is sorted by file offset, keeping this index
1126 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001127 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001128 unsigned NextValidReloc;
1129
1130 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1131 const DebugMapObject &DMO);
1132
1133 bool findValidRelocs(const object::SectionRef &Section,
1134 const object::ObjectFile &Obj,
1135 const DebugMapObject &DMO);
1136
1137 void findValidRelocsMachO(const object::SectionRef &Section,
1138 const object::MachOObjectFile &Obj,
1139 const DebugMapObject &DMO);
1140 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001141
Frederic Riss84c09a52015-02-13 23:18:34 +00001142 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1143 ///
1144 /// @{
1145 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1146 /// keep. Store that information in \p CU's DIEInfo.
1147 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1148 const DebugMapObject &DMO, CompileUnit &CU,
1149 unsigned Flags);
1150
1151 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1152 enum TravesalFlags {
1153 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1154 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1155 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1156 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001157 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss84c09a52015-02-13 23:18:34 +00001158 };
1159
1160 /// \brief Mark the passed DIE as well as all the ones it depends on
1161 /// as kept.
1162 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1163 CompileUnit::DIEInfo &MyInfo,
1164 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001165 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001166
1167 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1168 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1169 unsigned Flags);
1170
1171 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1172 CompileUnit &Unit,
1173 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1174
1175 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1176 CompileUnit &Unit,
1177 CompileUnit::DIEInfo &MyInfo,
1178 unsigned Flags);
1179
1180 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1181 CompileUnit::DIEInfo &Info);
1182 /// @}
1183
Frederic Rissb8b43d52015-03-04 22:07:44 +00001184 /// \defgroup Linking Methods used to link the debug information
1185 ///
1186 /// @{
1187 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1188 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1189 /// stripped out and addresses have been rewritten according to the
1190 /// debug map.
1191 ///
1192 /// \param OutOffset is the offset the cloned DIE in the output
1193 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001194 /// \param PCOffset (while cloning a function scope) is the offset
1195 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001196 ///
1197 /// \returns the root of the cloned tree.
1198 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001199 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001200
1201 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1202
Frederic Riss31da3242015-03-11 18:45:52 +00001203 /// \brief Information gathered and exchanged between the various
1204 /// clone*Attributes helpers about the attributes of a particular DIE.
1205 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001206 const char *Name, *MangledName; ///< Names.
1207 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1208
Frederic Riss7b5563a2015-08-31 01:43:14 +00001209 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
Frederic Riss31da3242015-03-11 18:45:52 +00001210 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1211 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1212
Frederic Rissbce93ff2015-03-16 02:05:10 +00001213 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1214 bool IsDeclaration; ///< Is this DIE only a declaration?
1215
1216 AttributesInfo()
1217 : Name(nullptr), MangledName(nullptr), NameOffset(0),
Frederic Riss7b5563a2015-08-31 01:43:14 +00001218 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1219 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001220 };
1221
Frederic Rissb8b43d52015-03-04 22:07:44 +00001222 /// \brief Helper for cloneDIE.
1223 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1224 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001225 const AttributeSpec AttrSpec, unsigned AttrSize,
1226 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001227
1228 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001229 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1230 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001231
1232 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001233 unsigned
1234 cloneDieReferenceAttribute(DIE &Die,
1235 const DWARFDebugInfoEntryMinimal &InputDIE,
1236 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001237 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001238
1239 /// \brief Helper for cloneDIE.
1240 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1241 const DWARFFormValue &Val, unsigned AttrSize);
1242
1243 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001244 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1245 const DWARFFormValue &Val,
1246 const CompileUnit &Unit, AttributesInfo &Info);
1247
1248 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001249 unsigned cloneScalarAttribute(DIE &Die,
1250 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001251 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001252 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001253 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001254
Frederic Riss23e20e92015-03-07 01:25:09 +00001255 /// \brief Helper for cloneDIE.
1256 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1257 bool isLittleEndian);
1258
Frederic Rissb8b43d52015-03-04 22:07:44 +00001259 /// \brief Assign an abbreviation number to \p Abbrev
1260 void AssignAbbrev(DIEAbbrev &Abbrev);
1261
1262 /// \brief FoldingSet that uniques the abbreviations.
1263 FoldingSet<DIEAbbrev> AbbreviationsSet;
1264 /// \brief Storage for the unique Abbreviations.
1265 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1266 /// be changed to a vecot of unique_ptrs.
1267 std::vector<DIEAbbrev *> Abbreviations;
1268
Frederic Riss25440872015-03-13 23:30:31 +00001269 /// \brief Compute and emit debug_ranges section for \p Unit, and
1270 /// patch the attributes referencing it.
1271 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1272
1273 /// \brief Generate and emit the DW_AT_ranges attribute for a
1274 /// compile_unit if it had one.
1275 void generateUnitRanges(CompileUnit &Unit) const;
1276
Frederic Riss63786b02015-03-15 20:45:43 +00001277 /// \brief Extract the line tables fromt he original dwarf, extract
1278 /// the relevant parts according to the linked function ranges and
1279 /// emit the result in the debug_line section.
1280 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1281
Frederic Rissbce93ff2015-03-16 02:05:10 +00001282 /// \brief Emit the accelerator entries for \p Unit.
1283 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1284
Frederic Riss5a642072015-06-05 23:06:11 +00001285 /// \brief Patch the frame info for an object file and emit it.
1286 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1287 unsigned AddressSize);
1288
Frederic Rissb8b43d52015-03-04 22:07:44 +00001289 /// \brief DIELoc objects that need to be destructed (but not freed!).
1290 std::vector<DIELoc *> DIELocs;
1291 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1292 std::vector<DIEBlock *> DIEBlocks;
1293 /// \brief Allocator used for all the DIEValue objects.
1294 BumpPtrAllocator DIEAlloc;
1295 /// @}
1296
Frederic Riss1c650942015-07-21 22:41:43 +00001297 /// ODR Contexts for that link.
1298 DeclContextTree ODRContexts;
1299
Frederic Riss1b9da422015-02-13 23:18:29 +00001300 /// \defgroup Helpers Various helper methods.
1301 ///
1302 /// @{
1303 const DWARFDebugInfoEntryMinimal *
Frederic Riss1c650942015-07-21 22:41:43 +00001304 resolveDIEReference(const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001305 const DWARFDebugInfoEntryMinimal &DIE,
1306 CompileUnit *&ReferencedCU);
1307
1308 CompileUnit *getUnitForOffset(unsigned Offset);
1309
Frederic Rissbce93ff2015-03-16 02:05:10 +00001310 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1311 AttributesInfo &Info);
1312
Frederic Riss1b9da422015-02-13 23:18:29 +00001313 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001314 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001315
1316 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001317
1318 /// \brief Attempt to load a debug object from disk.
1319 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1320 DebugMapObject &Obj,
1321 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001322 /// @}
1323
Frederic Riss563cba62015-01-28 22:15:14 +00001324private:
Frederic Rissd3455182015-01-28 18:27:01 +00001325 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001326 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001327 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001328 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001329
1330 /// The units of the current debug map object.
1331 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001332
1333 /// The debug map object curently under consideration.
1334 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001335
1336 /// \brief The Dwarf string pool
1337 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001338
1339 /// \brief This map is keyed by the entry PC of functions in that
1340 /// debug object and the associated value is a pair storing the
1341 /// corresponding end PC and the offset to apply to get the linked
1342 /// address.
1343 ///
1344 /// See startDebugObject() for a more complete description of its use.
1345 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001346
1347 /// \brief The CIEs that have been emitted in the output
1348 /// section. The actual CIE data serves a the key to this StringMap,
1349 /// this takes care of comparing the semantics of CIEs defined in
1350 /// different object files.
1351 StringMap<uint32_t> EmittedCIEs;
1352
1353 /// Offset of the last CIE that has been emitted in the output
1354 /// debug_frame section.
1355 uint32_t LastCIEOffset;
Frederic Rissd3455182015-01-28 18:27:01 +00001356};
1357
Frederic Riss1b9da422015-02-13 23:18:29 +00001358/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1359/// returning our CompileUnit object instead.
1360CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1361 auto CU =
1362 std::upper_bound(Units.begin(), Units.end(), Offset,
1363 [](uint32_t LHS, const CompileUnit &RHS) {
1364 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1365 });
1366 return CU != Units.end() ? &*CU : nullptr;
1367}
1368
1369/// \brief Resolve the DIE attribute reference that has been
1370/// extracted in \p RefValue. The resulting DIE migh be in another
1371/// CompileUnit which is stored into \p ReferencedCU.
1372/// \returns null if resolving fails for any reason.
1373const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
Frederic Riss1c650942015-07-21 22:41:43 +00001374 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001375 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1376 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1377 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1378
1379 if ((RefCU = getUnitForOffset(RefOffset)))
1380 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1381 return RefDie;
1382
1383 reportWarning("could not find referenced DIE", &Unit, &DIE);
1384 return nullptr;
1385}
1386
Frederic Riss1c650942015-07-21 22:41:43 +00001387/// \returns whether the passed \a Attr type might contain a DIE
1388/// reference suitable for ODR uniquing.
1389static bool isODRAttribute(uint16_t Attr) {
1390 switch (Attr) {
1391 default:
1392 return false;
1393 case dwarf::DW_AT_type:
1394 case dwarf::DW_AT_containing_type:
1395 case dwarf::DW_AT_specification:
1396 case dwarf::DW_AT_abstract_origin:
1397 case dwarf::DW_AT_import:
1398 return true;
1399 }
1400 llvm_unreachable("Improper attribute.");
1401}
1402
1403/// Set the last DIE/CU a context was seen in and, possibly invalidate
1404/// the context if it is ambiguous.
1405///
1406/// In the current implementation, we don't handle overloaded
1407/// functions well, because the argument types are not taken into
1408/// account when computing the DeclContext tree.
1409///
1410/// Some of this is mitigated byt using mangled names that do contain
1411/// the arguments types, but sometimes (eg. with function templates)
1412/// we don't have that. In that case, just do not unique anything that
1413/// refers to the contexts we are not able to distinguish.
1414///
1415/// If a context that is not a namespace appears twice in the same CU,
1416/// we know it is ambiguous. Make it invalid.
1417bool DeclContext::setLastSeenDIE(CompileUnit &U,
1418 const DWARFDebugInfoEntryMinimal *Die) {
1419 if (LastSeenCompileUnitID == U.getUniqueID()) {
1420 DWARFUnit &OrigUnit = U.getOrigUnit();
1421 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1422 U.getInfo(FirstIdx).Ctxt = nullptr;
1423 return false;
1424 }
1425
1426 LastSeenCompileUnitID = U.getUniqueID();
1427 LastSeenDIE = Die;
1428 return true;
1429}
1430
1431/// Get the child context of \a Context corresponding to \a DIE.
1432///
1433/// \returns the child context or null if we shouldn't track children
1434/// contexts. It also returns an additional bit meaning 'invalid'. An
1435/// invalid context means it shouldn't be considered for uniquing, but
1436/// its not returning null, because some children of that context
1437/// might be uniquing candidates.
1438/// FIXME: this is for dsymutil-classic compatibility, I don't think
1439/// it buys us much.
1440PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1441 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1442 NonRelocatableStringpool &StringPool) {
1443 unsigned Tag = DIE->getTag();
1444
1445 // FIXME: dsymutil-classic compat: We should bail out here if we
1446 // have a specification or an abstract_origin. We will get the
1447 // parent context wrong here.
1448
1449 switch (Tag) {
1450 default:
1451 // By default stop gathering child contexts.
1452 return PointerIntPair<DeclContext *, 1>(nullptr);
1453 case dwarf::DW_TAG_compile_unit:
1454 // FIXME: Add support for DW_TAG_module.
1455 return PointerIntPair<DeclContext *, 1>(&Context);
1456 case dwarf::DW_TAG_subprogram:
1457 // Do not unique anything inside CU local functions.
1458 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1459 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1460 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1461 dwarf::DW_AT_external, 0))
1462 return PointerIntPair<DeclContext *, 1>(nullptr);
1463 // Fallthrough
1464 case dwarf::DW_TAG_member:
1465 case dwarf::DW_TAG_namespace:
1466 case dwarf::DW_TAG_structure_type:
1467 case dwarf::DW_TAG_class_type:
1468 case dwarf::DW_TAG_union_type:
1469 case dwarf::DW_TAG_enumeration_type:
1470 case dwarf::DW_TAG_typedef:
1471 // Artificial things might be ambiguous, because they might be
1472 // created on demand. For example implicitely defined constructors
1473 // are ambiguous because of the way we identify contexts, and they
1474 // won't be generated everytime everywhere.
1475 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1476 dwarf::DW_AT_artificial, 0))
1477 return PointerIntPair<DeclContext *, 1>(nullptr);
1478 break;
1479 }
1480
1481 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1482 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1483 StringRef NameRef;
1484 StringRef ShortNameRef;
1485 StringRef FileRef;
1486
1487 if (Name)
1488 NameRef = StringPool.internString(Name);
1489 else if (Tag == dwarf::DW_TAG_namespace)
1490 // FIXME: For dsymutil-classic compatibility. I think uniquing
1491 // within anonymous namespaces is wrong. There is no ODR guarantee
1492 // there.
1493 NameRef = StringPool.internString("(anonymous namespace)");
1494
1495 if (ShortName && ShortName != Name)
1496 ShortNameRef = StringPool.internString(ShortName);
1497 else
1498 ShortNameRef = NameRef;
1499
1500 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1501 Tag != dwarf::DW_TAG_union_type &&
1502 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1503 return PointerIntPair<DeclContext *, 1>(nullptr);
1504
1505 std::string File;
1506 unsigned Line = 0;
1507 unsigned ByteSize = 0;
1508
1509 // Gather some discriminating data about the DeclContext we will be
1510 // creating: File, line number and byte size. This shouldn't be
1511 // necessary, because the ODR is just about names, but given that we
1512 // do some approximations with overloaded functions and anonymous
1513 // namespaces, use these additional data points to make the process safer.
1514 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1515 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1516 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1517 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1518 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1519 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1520 &U.getOrigUnit())) {
1521 // FIXME: dsymutil-classic compatibility. I'd rather not
1522 // unique anything in anonymous namespaces, but if we do, then
1523 // verify that the file and line correspond.
1524 if (!Name && Tag == dwarf::DW_TAG_namespace)
1525 FileNum = 1;
1526
1527 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1528 // instead of "" would allow more uniquing, but for now, do
1529 // it this way to match dsymutil-classic.
1530 if (LT->getFileNameByIndex(
1531 FileNum, "",
1532 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1533 File)) {
1534 Line = DIE->getAttributeValueAsUnsignedConstant(
1535 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1536#ifdef HAVE_REALPATH
1537 // Cache the resolved paths, because calling realpath is expansive.
1538 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1539 File = ResolvedPath;
1540 } else {
1541 char RealPath[PATH_MAX + 1];
1542 RealPath[PATH_MAX] = 0;
1543 if (::realpath(File.c_str(), RealPath))
1544 File = RealPath;
1545 U.setResolvedPath(FileNum, File);
1546 }
1547#endif
1548 FileRef = StringPool.internString(File);
1549 }
1550 }
1551 }
1552 }
1553
1554 if (!Line && NameRef.empty())
1555 return PointerIntPair<DeclContext *, 1>(nullptr);
1556
1557 // FIXME: dsymutil-classic compat won't unique the same type
1558 // presented once as a struct and once as a class. Use the Tag in
1559 // the fully qualified name hash to get the same effect.
1560 // We hash NameRef, which is the mangled name, in order to get most
1561 // overloaded functions resolvec correctly.
1562 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1563
1564 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1565 // use the filename.
1566 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1567 Hash = hash_combine(Hash, FileRef);
1568
1569 // Now look if this context already exists.
1570 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1571 auto ContextIter = Contexts.find(&Key);
1572
1573 if (ContextIter == Contexts.end()) {
1574 // The context wasn't found.
1575 bool Inserted;
1576 DeclContext *NewContext =
1577 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1578 Context, DIE, U.getUniqueID());
1579 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1580 assert(Inserted && "Failed to insert DeclContext");
1581 (void)Inserted;
1582 } else if (Tag != dwarf::DW_TAG_namespace &&
1583 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1584 // The context was found, but it is ambiguous with another context
1585 // in the same file. Mark it invalid.
1586 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1587 }
1588
1589 assert(ContextIter != Contexts.end());
1590 // FIXME: dsymutil-classic compatibility. Union types aren't
1591 // uniques, but their children might be.
1592 if ((Tag == dwarf::DW_TAG_subprogram &&
1593 Context.getTag() != dwarf::DW_TAG_structure_type &&
1594 Context.getTag() != dwarf::DW_TAG_class_type) ||
1595 (Tag == dwarf::DW_TAG_union_type))
1596 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1597
1598 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1599}
1600
Frederic Rissbce93ff2015-03-16 02:05:10 +00001601/// \brief Get the potential name and mangled name for the entity
1602/// described by \p Die and store them in \Info if they are not
1603/// already there.
1604/// \returns is a name was found.
1605bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1606 DWARFUnit &U, AttributesInfo &Info) {
1607 // FIXME: a bit wastefull as the first getName might return the
1608 // short name.
1609 if (!Info.MangledName &&
1610 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1611 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1612
1613 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1614 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1615
1616 return Info.Name || Info.MangledName;
1617}
1618
Frederic Riss1b9da422015-02-13 23:18:29 +00001619/// \brief Report a warning to the user, optionaly including
1620/// information about a specific \p DIE related to the warning.
1621void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001622 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001623 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001624 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001625 Context = CurrentDebugObject->getObjectFilename();
1626 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001627
Frederic Rissb9818322015-02-28 00:29:07 +00001628 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001629 return;
1630
1631 errs() << " in DIE:\n";
1632 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1633 6 /* Indent */);
1634}
1635
Frederic Rissc99ea202015-02-28 00:29:11 +00001636bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1637 if (Options.NoOutput)
1638 return true;
1639
Frederic Rissb52cf522015-02-28 00:42:37 +00001640 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001641 return Streamer->init(TheTriple, OutputFilename);
1642}
1643
Frederic Riss563cba62015-01-28 22:15:14 +00001644/// \brief Recursive helper to gather the child->parent relationships in the
1645/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001646static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
Frederic Riss1c650942015-07-21 22:41:43 +00001647 unsigned ParentIdx, CompileUnit &CU,
1648 DeclContext *CurrentDeclContext,
1649 NonRelocatableStringpool &StringPool,
1650 DeclContextTree &Contexts) {
Frederic Riss563cba62015-01-28 22:15:14 +00001651 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001652 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1653
1654 Info.ParentIdx = ParentIdx;
1655 if (CU.hasODR()) {
1656 if (CurrentDeclContext) {
1657 auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1658 DIE, CU, StringPool);
1659 CurrentDeclContext = PtrInvalidPair.getPointer();
1660 Info.Ctxt =
1661 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1662 } else
1663 Info.Ctxt = CurrentDeclContext = nullptr;
1664 }
Frederic Riss563cba62015-01-28 22:15:14 +00001665
1666 if (DIE->hasChildren())
1667 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1668 Child = Child->getSibling())
Frederic Riss1c650942015-07-21 22:41:43 +00001669 gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1670 Contexts);
Frederic Riss563cba62015-01-28 22:15:14 +00001671}
1672
Frederic Riss84c09a52015-02-13 23:18:34 +00001673static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1674 switch (Tag) {
1675 default:
1676 return false;
1677 case dwarf::DW_TAG_subprogram:
1678 case dwarf::DW_TAG_lexical_block:
1679 case dwarf::DW_TAG_subroutine_type:
1680 case dwarf::DW_TAG_structure_type:
1681 case dwarf::DW_TAG_class_type:
1682 case dwarf::DW_TAG_union_type:
1683 return true;
1684 }
1685 llvm_unreachable("Invalid Tag");
1686}
1687
Frederic Riss1c650942015-07-21 22:41:43 +00001688static unsigned getRefAddrSize(const DWARFUnit &U) {
1689 if (U.getVersion() == 2)
1690 return U.getAddressByteSize();
1691 return 4;
1692}
1693
Frederic Riss63786b02015-03-15 20:45:43 +00001694void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001695 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001696 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001697 // Iterate over the debug map entries and put all the ones that are
1698 // functions (because they have a size) into the Ranges map. This
1699 // map is very similar to the FunctionRanges that are stored in each
1700 // unit, with 2 notable differences:
1701 // - obviously this one is global, while the other ones are per-unit.
1702 // - this one contains not only the functions described in the DIE
1703 // tree, but also the ones that are only in the debug map.
1704 // The latter information is required to reproduce dsymutil's logic
1705 // while linking line tables. The cases where this information
1706 // matters look like bugs that need to be investigated, but for now
1707 // we need to reproduce dsymutil's behavior.
1708 // FIXME: Once we understood exactly if that information is needed,
1709 // maybe totally remove this (or try to use it to do a real
1710 // -gline-tables-only on Darwin.
1711 for (const auto &Entry : Obj.symbols()) {
1712 const auto &Mapping = Entry.getValue();
1713 if (Mapping.Size)
1714 Ranges[Mapping.ObjectAddress] = std::make_pair(
1715 Mapping.ObjectAddress + Mapping.Size,
1716 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1717 }
Frederic Riss563cba62015-01-28 22:15:14 +00001718}
1719
Frederic Riss1036e642015-02-13 23:18:22 +00001720void DwarfLinker::endDebugObject() {
1721 Units.clear();
1722 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001723 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001724
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001725 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1726 (*I)->~DIEBlock();
1727 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1728 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001729
1730 DIEBlocks.clear();
1731 DIELocs.clear();
1732 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001733}
1734
1735/// \brief Iterate over the relocations of the given \p Section and
1736/// store the ones that correspond to debug map entries into the
1737/// ValidRelocs array.
1738void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1739 const object::MachOObjectFile &Obj,
1740 const DebugMapObject &DMO) {
1741 StringRef Contents;
1742 Section.getContents(Contents);
1743 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1744
1745 for (const object::RelocationRef &Reloc : Section.relocations()) {
1746 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1747 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1748 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001749 uint64_t Offset64 = Reloc.getOffset();
1750 if ((RelocSize != 4 && RelocSize != 8)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001751 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001752 continue;
1753 }
1754 uint32_t Offset = Offset64;
1755 // Mach-o uses REL relocations, the addend is at the relocation offset.
1756 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1757
1758 auto Sym = Reloc.getSymbol();
1759 if (Sym != Obj.symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001760 ErrorOr<StringRef> SymbolName = Sym->getName();
1761 if (!SymbolName) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001762 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001763 continue;
1764 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001765 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001766 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1767 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1768 // Do not store the addend. The addend was the address of the
1769 // symbol in the object file, the address in the binary that is
1770 // stored in the debug map doesn't need to be offseted.
1771 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1772 }
1773 }
1774}
1775
1776/// \brief Dispatch the valid relocation finding logic to the
1777/// appropriate handler depending on the object file format.
1778bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1779 const object::ObjectFile &Obj,
1780 const DebugMapObject &DMO) {
1781 // Dispatch to the right handler depending on the file type.
1782 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1783 findValidRelocsMachO(Section, *MachOObj, DMO);
1784 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001785 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001786
1787 if (ValidRelocs.empty())
1788 return false;
1789
1790 // Sort the relocations by offset. We will walk the DIEs linearly in
1791 // the file, this allows us to just keep an index in the relocation
1792 // array that we advance during our walk, rather than resorting to
1793 // some associative container. See DwarfLinker::NextValidReloc.
1794 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1795 return true;
1796}
1797
1798/// \brief Look for relocations in the debug_info section that match
1799/// entries in the debug map. These relocations will drive the Dwarf
1800/// link by indicating which DIEs refer to symbols present in the
1801/// linked binary.
1802/// \returns wether there are any valid relocations in the debug info.
1803bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1804 const DebugMapObject &DMO) {
1805 // Find the debug_info section.
1806 for (const object::SectionRef &Section : Obj.sections()) {
1807 StringRef SectionName;
1808 Section.getName(SectionName);
1809 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1810 if (SectionName != "debug_info")
1811 continue;
1812 return findValidRelocs(Section, Obj, DMO);
1813 }
1814 return false;
1815}
Frederic Riss563cba62015-01-28 22:15:14 +00001816
Frederic Riss84c09a52015-02-13 23:18:34 +00001817/// \brief Checks that there is a relocation against an actual debug
1818/// map entry between \p StartOffset and \p NextOffset.
1819///
1820/// This function must be called with offsets in strictly ascending
1821/// order because it never looks back at relocations it already 'went past'.
1822/// \returns true and sets Info.InDebugMap if it is the case.
1823bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1824 CompileUnit::DIEInfo &Info) {
1825 assert(NextValidReloc == 0 ||
1826 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1827 if (NextValidReloc >= ValidRelocs.size())
1828 return false;
1829
1830 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1831
1832 // We might need to skip some relocs that we didn't consider. For
1833 // example the high_pc of a discarded DIE might contain a reloc that
1834 // is in the list because it actually corresponds to the start of a
1835 // function that is in the debug map.
1836 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1837 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1838
1839 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1840 return false;
1841
1842 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001843 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissb9818322015-02-28 00:29:07 +00001844 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001845 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1846 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001847 uint64_t(Mapping.ObjectAddress),
1848 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001849
Frederic Rissf37964c2015-06-05 20:27:07 +00001850 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1851 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001852 Info.InDebugMap = true;
1853 return true;
1854}
1855
1856/// \brief Get the starting and ending (exclusive) offset for the
1857/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1858/// supposed to point to the position of the first attribute described
1859/// by \p Abbrev.
1860/// \return [StartOffset, EndOffset) as a pair.
1861static std::pair<uint32_t, uint32_t>
1862getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1863 unsigned Offset, const DWARFUnit &Unit) {
1864 DataExtractor Data = Unit.getDebugInfoExtractor();
1865
1866 for (unsigned i = 0; i < Idx; ++i)
1867 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1868
1869 uint32_t End = Offset;
1870 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1871
1872 return std::make_pair(Offset, End);
1873}
1874
1875/// \brief Check if a variable describing DIE should be kept.
1876/// \returns updated TraversalFlags.
1877unsigned DwarfLinker::shouldKeepVariableDIE(
1878 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1879 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1880 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1881
1882 // Global variables with constant value can always be kept.
1883 if (!(Flags & TF_InFunctionScope) &&
1884 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1885 MyInfo.InDebugMap = true;
1886 return Flags | TF_Keep;
1887 }
1888
1889 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1890 if (LocationIdx == -1U)
1891 return Flags;
1892
1893 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1894 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1895 uint32_t LocationOffset, LocationEndOffset;
1896 std::tie(LocationOffset, LocationEndOffset) =
1897 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1898
1899 // See if there is a relocation to a valid debug map entry inside
1900 // this variable's location. The order is important here. We want to
1901 // always check in the variable has a valid relocation, so that the
1902 // DIEInfo is filled. However, we don't want a static variable in a
1903 // function to force us to keep the enclosing function.
1904 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1905 (Flags & TF_InFunctionScope))
1906 return Flags;
1907
Frederic Rissb9818322015-02-28 00:29:07 +00001908 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001909 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1910
1911 return Flags | TF_Keep;
1912}
1913
1914/// \brief Check if a function describing DIE should be kept.
1915/// \returns updated TraversalFlags.
1916unsigned DwarfLinker::shouldKeepSubprogramDIE(
1917 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1918 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1919 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1920
1921 Flags |= TF_InFunctionScope;
1922
1923 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1924 if (LowPcIdx == -1U)
1925 return Flags;
1926
1927 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1928 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1929 uint32_t LowPcOffset, LowPcEndOffset;
1930 std::tie(LowPcOffset, LowPcEndOffset) =
1931 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1932
1933 uint64_t LowPc =
1934 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1935 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1936 if (LowPc == -1ULL ||
1937 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1938 return Flags;
1939
Frederic Rissb9818322015-02-28 00:29:07 +00001940 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001941 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1942
Frederic Riss1af75f72015-03-12 18:45:10 +00001943 Flags |= TF_Keep;
1944
1945 DWARFFormValue HighPcValue;
1946 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1947 reportWarning("Function without high_pc. Range will be discarded.\n",
1948 &OrigUnit, &DIE);
1949 return Flags;
1950 }
1951
1952 uint64_t HighPc;
1953 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1954 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1955 } else {
1956 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1957 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1958 }
1959
Frederic Riss63786b02015-03-15 20:45:43 +00001960 // Replace the debug map range with a more accurate one.
1961 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001962 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1963 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001964}
1965
1966/// \brief Check if a DIE should be kept.
1967/// \returns updated TraversalFlags.
1968unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1969 CompileUnit &Unit,
1970 CompileUnit::DIEInfo &MyInfo,
1971 unsigned Flags) {
1972 switch (DIE.getTag()) {
1973 case dwarf::DW_TAG_constant:
1974 case dwarf::DW_TAG_variable:
1975 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1976 case dwarf::DW_TAG_subprogram:
1977 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1978 case dwarf::DW_TAG_module:
1979 case dwarf::DW_TAG_imported_module:
1980 case dwarf::DW_TAG_imported_declaration:
1981 case dwarf::DW_TAG_imported_unit:
1982 // We always want to keep these.
1983 return Flags | TF_Keep;
1984 }
1985
1986 return Flags;
1987}
1988
Frederic Riss84c09a52015-02-13 23:18:34 +00001989/// \brief Mark the passed DIE as well as all the ones it depends on
1990/// as kept.
1991///
1992/// This function is called by lookForDIEsToKeep on DIEs that are
1993/// newly discovered to be needed in the link. It recursively calls
1994/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1995/// TraversalFlags to inform it that it's not doing the primary DIE
1996/// tree walk.
1997void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1998 CompileUnit::DIEInfo &MyInfo,
1999 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002000 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002001 const DWARFUnit &Unit = CU.getOrigUnit();
2002 MyInfo.Keep = true;
2003
2004 // First mark all the parent chain as kept.
2005 unsigned AncestorIdx = MyInfo.ParentIdx;
2006 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002007 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Frederic Riss84c09a52015-02-13 23:18:34 +00002008 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002009 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002010 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2011 }
2012
2013 // Then we need to mark all the DIEs referenced by this DIE's
2014 // attributes as kept.
2015 DataExtractor Data = Unit.getDebugInfoExtractor();
2016 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2017 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2018
2019 // Mark all DIEs referenced through atttributes as kept.
2020 for (const auto &AttrSpec : Abbrev->attributes()) {
2021 DWARFFormValue Val(AttrSpec.Form);
2022
2023 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2024 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2025 continue;
2026 }
2027
2028 Val.extractValue(Data, &Offset, &Unit);
2029 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002030 if (const auto *RefDIE =
2031 resolveDIEReference(Val, Unit, DIE, ReferencedCU)) {
2032 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2033 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2034 // If the referenced DIE has a DeclContext that has already been
2035 // emitted, then do not keep the one in this CU. We'll link to
2036 // the canonical DIE in cloneDieReferenceAttribute.
2037 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2038 // be necessary and could be advantageously replaced by
2039 // ReferencedCU->hasODR() && CU.hasODR().
2040 // FIXME: compatibility with dsymutil-classic. There is no
2041 // reason not to unique ref_addr references.
2042 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2043 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2044 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2045 continue;
2046
2047 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Frederic Riss84c09a52015-02-13 23:18:34 +00002048 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002049 TF_Keep | TF_DependencyWalk | ODRFlag);
2050 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002051 }
2052}
2053
2054/// \brief Recursively walk the \p DIE tree and look for DIEs to
2055/// keep. Store that information in \p CU's DIEInfo.
2056///
2057/// This function is the entry point of the DIE selection
2058/// algorithm. It is expected to walk the DIE tree in file order and
2059/// (though the mediation of its helper) call hasValidRelocation() on
2060/// each DIE that might be a 'root DIE' (See DwarfLinker class
2061/// comment).
2062/// While walking the dependencies of root DIEs, this function is
2063/// also called, but during these dependency walks the file order is
2064/// not respected. The TF_DependencyWalk flag tells us which kind of
2065/// traversal we are currently doing.
2066void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
2067 const DebugMapObject &DMO, CompileUnit &CU,
2068 unsigned Flags) {
2069 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
2070 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2071 bool AlreadyKept = MyInfo.Keep;
2072
2073 // If the Keep flag is set, we are marking a required DIE's
2074 // dependencies. If our target is already marked as kept, we're all
2075 // set.
2076 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2077 return;
2078
2079 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2080 // because it would screw up the relocation finding logic.
2081 if (!(Flags & TF_DependencyWalk))
2082 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
2083
2084 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002085 if (!AlreadyKept && (Flags & TF_Keep)) {
2086 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2087 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, UseOdr);
2088 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002089 // The TF_ParentWalk flag tells us that we are currently walking up
2090 // the parent chain of a required DIE, and we don't want to mark all
2091 // the children of the parents as kept (consider for example a
2092 // DW_TAG_namespace node in the parent chain). There are however a
2093 // set of DIE types for which we want to ignore that directive and still
2094 // walk their children.
2095 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
2096 Flags &= ~TF_ParentWalk;
2097
2098 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
2099 return;
2100
2101 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
2102 Child = Child->getSibling())
2103 lookForDIEsToKeep(*Child, DMO, CU, Flags);
2104}
2105
Frederic Rissb8b43d52015-03-04 22:07:44 +00002106/// \brief Assign an abbreviation numer to \p Abbrev.
2107///
2108/// Our DIEs get freed after every DebugMapObject has been processed,
2109/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2110/// the instances hold by the DIEs. When we encounter an abbreviation
2111/// that we don't know, we create a permanent copy of it.
2112void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2113 // Check the set for priors.
2114 FoldingSetNodeID ID;
2115 Abbrev.Profile(ID);
2116 void *InsertToken;
2117 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2118
2119 // If it's newly added.
2120 if (InSet) {
2121 // Assign existing abbreviation number.
2122 Abbrev.setNumber(InSet->getNumber());
2123 } else {
2124 // Add to abbreviation list.
2125 Abbreviations.push_back(
2126 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2127 for (const auto &Attr : Abbrev.getData())
2128 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2129 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2130 // Assign the unique abbreviation number.
2131 Abbrev.setNumber(Abbreviations.size());
2132 Abbreviations.back()->setNumber(Abbreviations.size());
2133 }
2134}
2135
2136/// \brief Clone a string attribute described by \p AttrSpec and add
2137/// it to \p Die.
2138/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00002139unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
2140 const DWARFFormValue &Val,
2141 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002142 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002143 const char *String = *Val.getAsCString(&U);
2144 unsigned Offset = StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002145 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002146 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002147 return 4;
2148}
2149
2150/// \brief Clone an attribute referencing another DIE and add
2151/// it to \p Die.
2152/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00002153unsigned DwarfLinker::cloneDieReferenceAttribute(
2154 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2155 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002156 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002157 const DWARFUnit &U = Unit.getOrigUnit();
2158 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002159 DIE *NewRefDie = nullptr;
2160 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002161 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002162
Frederic Riss1c650942015-07-21 22:41:43 +00002163 const DWARFDebugInfoEntryMinimal *RefDie =
2164 resolveDIEReference(Val, U, InputDIE, RefUnit);
2165
2166 // If the referenced DIE is not found, drop the attribute.
2167 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002168 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002169
2170 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2171 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002172
2173 // If we already have emitted an equivalent DeclContext, just point
2174 // at it.
2175 if (isODRAttribute(AttrSpec.Attr)) {
2176 Ctxt = RefInfo.Ctxt;
2177 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2178 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2179 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2180 dwarf::DW_FORM_ref_addr, Attr);
2181 return getRefAddrSize(U);
2182 }
2183 }
2184
Frederic Riss9833de62015-03-06 23:22:53 +00002185 if (!RefInfo.Clone) {
2186 assert(Ref > InputDIE.getOffset());
2187 // We haven't cloned this DIE yet. Just create an empty one and
2188 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002189 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002190 }
2191 NewRefDie = RefInfo.Clone;
2192
Frederic Riss1c650942015-07-21 22:41:43 +00002193 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2194 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002195 // We cannot currently rely on a DIEEntry to emit ref_addr
2196 // references, because the implementation calls back to DwarfDebug
2197 // to find the unit offset. (We don't have a DwarfDebug)
2198 // FIXME: we should be able to design DIEEntry reliance on
2199 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002200 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002201 if (Ref < InputDIE.getOffset()) {
2202 // We must have already cloned that DIE.
2203 uint32_t NewRefOffset =
2204 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002205 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002206 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2207 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002208 } else {
2209 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002210 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002211 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002212 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002213 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2214 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002215 }
Frederic Riss1c650942015-07-21 22:41:43 +00002216 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002217 }
2218
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002219 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2220 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002221 return AttrSize;
2222}
2223
2224/// \brief Clone an attribute of block form (locations, constants) and add
2225/// it to \p Die.
2226/// \returns the size of the new attribute.
2227unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
2228 const DWARFFormValue &Val,
2229 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002230 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002231 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002232 DIELoc *Loc = nullptr;
2233 DIEBlock *Block = nullptr;
2234 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002235 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002236 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002237 DIELocs.push_back(Loc);
2238 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002239 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002240 DIEBlocks.push_back(Block);
2241 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002242 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2243 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002244
2245 if (Loc)
2246 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2247 dwarf::Form(AttrSpec.Form), Loc);
2248 else
2249 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2250 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002251 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2252 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002253 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2254 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002255 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2256 // the DIE class, this if could be replaced by
2257 // Attr->setSize(Bytes.size()).
2258 if (Streamer) {
2259 if (Loc)
2260 Loc->ComputeSize(&Streamer->getAsmPrinter());
2261 else
2262 Block->ComputeSize(&Streamer->getAsmPrinter());
2263 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002264 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002265 return AttrSize;
2266}
2267
Frederic Riss31da3242015-03-11 18:45:52 +00002268/// \brief Clone an address attribute and add it to \p Die.
2269/// \returns the size of the new attribute.
2270unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
2271 const DWARFFormValue &Val,
2272 const CompileUnit &Unit,
2273 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002274 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002275 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2276 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2277 Die.getTag() == dwarf::DW_TAG_lexical_block)
Frederic Riss7b5563a2015-08-31 01:43:14 +00002278 // The low_pc of a block or inline subroutine might get
2279 // relocated because it happens to match the low_pc of the
2280 // enclosing subprogram. To prevent issues with that, always use
2281 // the low_pc from the input DIE if relocations have been applied.
2282 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2283 Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002284 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2285 Addr = Unit.getLowPc();
2286 if (Addr == UINT64_MAX)
2287 return 0;
2288 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002289 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002290 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002291 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2292 if (uint64_t HighPc = Unit.getHighPc())
2293 Addr = HighPc;
2294 else
2295 return 0;
2296 } else
2297 // If we have a high_pc recorded for the input DIE, use
2298 // it. Otherwise (when no relocations where applied) just use the
2299 // one we just decoded.
2300 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002301 }
2302
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002303 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002304 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002305 return Unit.getOrigUnit().getAddressByteSize();
2306}
2307
Frederic Rissb8b43d52015-03-04 22:07:44 +00002308/// \brief Clone a scalar attribute and add it to \p Die.
2309/// \returns the size of the new attribute.
2310unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002311 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002312 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002313 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002314 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002315 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2316 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2317 if (Unit.getLowPc() == -1ULL)
2318 return 0;
2319 // Dwarf >= 4 high_pc is an size, not an address.
2320 Value = Unit.getHighPc() - Unit.getLowPc();
2321 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002322 Value = *Val.getAsSectionOffset();
2323 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2324 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002325 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2326 Value = *OptionalValue;
2327 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002328 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2329 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002330 return 0;
2331 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002332 PatchLocation Patch =
2333 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2334 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002335 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002336 Unit.noteRangeAttribute(Die, Patch);
Frederic Rissdfb97902015-03-14 15:49:07 +00002337 // A more generic way to check for location attributes would be
2338 // nice, but it's very unlikely that any other attribute needs a
2339 // location list.
2340 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2341 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002342 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002343 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2344 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002345
Frederic Rissb8b43d52015-03-04 22:07:44 +00002346 return AttrSize;
2347}
2348
2349/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2350/// value \p Val, and add it to \p Die.
2351/// \returns the size of the cloned attribute.
2352unsigned DwarfLinker::cloneAttribute(DIE &Die,
2353 const DWARFDebugInfoEntryMinimal &InputDIE,
2354 CompileUnit &Unit,
2355 const DWARFFormValue &Val,
2356 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00002357 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002358 const DWARFUnit &U = Unit.getOrigUnit();
2359
2360 switch (AttrSpec.Form) {
2361 case dwarf::DW_FORM_strp:
2362 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002363 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002364 case dwarf::DW_FORM_ref_addr:
2365 case dwarf::DW_FORM_ref1:
2366 case dwarf::DW_FORM_ref2:
2367 case dwarf::DW_FORM_ref4:
2368 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002369 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002370 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002371 case dwarf::DW_FORM_block:
2372 case dwarf::DW_FORM_block1:
2373 case dwarf::DW_FORM_block2:
2374 case dwarf::DW_FORM_block4:
2375 case dwarf::DW_FORM_exprloc:
2376 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2377 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002378 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002379 case dwarf::DW_FORM_data1:
2380 case dwarf::DW_FORM_data2:
2381 case dwarf::DW_FORM_data4:
2382 case dwarf::DW_FORM_data8:
2383 case dwarf::DW_FORM_udata:
2384 case dwarf::DW_FORM_sdata:
2385 case dwarf::DW_FORM_sec_offset:
2386 case dwarf::DW_FORM_flag:
2387 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002388 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2389 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002390 default:
2391 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2392 &InputDIE);
2393 }
2394
2395 return 0;
2396}
2397
Frederic Riss23e20e92015-03-07 01:25:09 +00002398/// \brief Apply the valid relocations found by findValidRelocs() to
2399/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2400/// in the debug_info section.
2401///
2402/// Like for findValidRelocs(), this function must be called with
2403/// monotonic \p BaseOffset values.
2404///
2405/// \returns wether any reloc has been applied.
2406bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2407 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002408 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002409 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2410 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002411 if (NextValidReloc >= ValidRelocs.size())
2412 return false;
2413
2414 // Skip relocs that haven't been applied.
2415 while (NextValidReloc < ValidRelocs.size() &&
2416 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2417 ++NextValidReloc;
2418
2419 bool Applied = false;
2420 uint64_t EndOffset = BaseOffset + Data.size();
2421 while (NextValidReloc < ValidRelocs.size() &&
2422 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2423 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2424 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2425 assert(ValidReloc.Offset - BaseOffset < Data.size());
2426 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2427 char Buf[8];
2428 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2429 Value += ValidReloc.Addend;
2430 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2431 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2432 Buf[i] = uint8_t(Value >> (Index * 8));
2433 }
2434 assert(ValidReloc.Size <= sizeof(Buf));
2435 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2436 Applied = true;
2437 }
2438
2439 return Applied;
2440}
2441
Frederic Rissbce93ff2015-03-16 02:05:10 +00002442static bool isTypeTag(uint16_t Tag) {
2443 switch (Tag) {
2444 case dwarf::DW_TAG_array_type:
2445 case dwarf::DW_TAG_class_type:
2446 case dwarf::DW_TAG_enumeration_type:
2447 case dwarf::DW_TAG_pointer_type:
2448 case dwarf::DW_TAG_reference_type:
2449 case dwarf::DW_TAG_string_type:
2450 case dwarf::DW_TAG_structure_type:
2451 case dwarf::DW_TAG_subroutine_type:
2452 case dwarf::DW_TAG_typedef:
2453 case dwarf::DW_TAG_union_type:
2454 case dwarf::DW_TAG_ptr_to_member_type:
2455 case dwarf::DW_TAG_set_type:
2456 case dwarf::DW_TAG_subrange_type:
2457 case dwarf::DW_TAG_base_type:
2458 case dwarf::DW_TAG_const_type:
2459 case dwarf::DW_TAG_constant:
2460 case dwarf::DW_TAG_file_type:
2461 case dwarf::DW_TAG_namelist:
2462 case dwarf::DW_TAG_packed_type:
2463 case dwarf::DW_TAG_volatile_type:
2464 case dwarf::DW_TAG_restrict_type:
2465 case dwarf::DW_TAG_interface_type:
2466 case dwarf::DW_TAG_unspecified_type:
2467 case dwarf::DW_TAG_shared_type:
2468 return true;
2469 default:
2470 break;
2471 }
2472 return false;
2473}
2474
Frederic Rissb8b43d52015-03-04 22:07:44 +00002475/// \brief Recursively clone \p InputDIE's subtrees that have been
2476/// selected to appear in the linked output.
2477///
2478/// \param OutOffset is the Offset where the newly created DIE will
2479/// lie in the linked compile unit.
2480///
2481/// \returns the cloned DIE object or null if nothing was selected.
2482DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002483 CompileUnit &Unit, int64_t PCOffset,
2484 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002485 DWARFUnit &U = Unit.getOrigUnit();
2486 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002487 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002488
2489 // Should the DIE appear in the output?
2490 if (!Unit.getInfo(Idx).Keep)
2491 return nullptr;
2492
2493 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002494 // The DIE might have been already created by a forward reference
2495 // (see cloneDieReferenceAttribute()).
2496 DIE *Die = Info.Clone;
2497 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002498 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002499 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002500 Die->setOffset(OutOffset);
Frederic Riss1c650942015-07-21 22:41:43 +00002501 if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2502 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2503 !Info.Ctxt->getCanonicalDIEOffset()) {
2504 // We are about to emit a DIE that is the root of its own valid
2505 // DeclContext tree. Make the current offset the canonical offset
2506 // for this context.
2507 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2508 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002509
2510 // Extract and clone every attribute.
2511 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002512 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002513 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002514
2515 // We could copy the data only if we need to aply a relocation to
2516 // it. After testing, it seems there is no performance downside to
2517 // doing the copy unconditionally, and it makes the code simpler.
2518 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2519 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2520 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002521 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2522 // If we applied relocations, we store the value of high_pc that was
2523 // potentially stored in the input DIE. If high_pc is an address
2524 // (Dwarf version == 2), then it might have been relocated to a
2525 // totally unrelated value (because the end address in the object
2526 // file might be start address of another function which got moved
2527 // independantly by the linker). The computation of the actual
2528 // high_pc value is done in cloneAddressAttribute().
2529 AttrInfo.OrigHighPc =
2530 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
Frederic Riss7b5563a2015-08-31 01:43:14 +00002531 // Also store the low_pc. It might get relocated in an
2532 // inline_subprogram that happens at the beginning of its
2533 // inlining function.
2534 AttrInfo.OrigLowPc =
2535 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
Frederic Riss31da3242015-03-11 18:45:52 +00002536 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002537
2538 // Reset the Offset to 0 as we will be working on the local copy of
2539 // the data.
2540 Offset = 0;
2541
Frederic Rissb8b43d52015-03-04 22:07:44 +00002542 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2543 Offset += getULEB128Size(Abbrev->getCode());
2544
Frederic Riss31da3242015-03-11 18:45:52 +00002545 // We are entering a subprogram. Get and propagate the PCOffset.
2546 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2547 PCOffset = Info.AddrAdjust;
2548 AttrInfo.PCOffset = PCOffset;
2549
Frederic Rissb8b43d52015-03-04 22:07:44 +00002550 for (const auto &AttrSpec : Abbrev->attributes()) {
2551 DWARFFormValue Val(AttrSpec.Form);
2552 uint32_t AttrSize = Offset;
2553 Val.extractValue(Data, &Offset, &U);
2554 AttrSize = Offset - AttrSize;
2555
Frederic Riss31da3242015-03-11 18:45:52 +00002556 OutOffset +=
2557 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002558 }
2559
Frederic Rissbce93ff2015-03-16 02:05:10 +00002560 // Look for accelerator entries.
2561 uint16_t Tag = InputDIE.getTag();
2562 // FIXME: This is slightly wrong. An inline_subroutine without a
2563 // low_pc, but with AT_ranges might be interesting to get into the
2564 // accelerator tables too. For now stick with dsymutil's behavior.
2565 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2566 Tag != dwarf::DW_TAG_compile_unit &&
2567 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2568 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2569 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2570 AttrInfo.MangledNameOffset,
2571 Tag == dwarf::DW_TAG_inlined_subroutine);
2572 if (AttrInfo.Name)
2573 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2574 Tag == dwarf::DW_TAG_inlined_subroutine);
2575 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2576 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2577 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2578 }
2579
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002580 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002581 // If a scope DIE is kept, we must have kept at least one child. If
2582 // it's not the case, we'll just be emitting one wasteful end of
2583 // children marker, but things won't break.
2584 if (InputDIE.hasChildren())
2585 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2586 // Assign a permanent abbrev number
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002587 AssignAbbrev(NewAbbrev);
2588 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002589
2590 // Add the size of the abbreviation number to the output offset.
2591 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2592
2593 if (!Abbrev->hasChildren()) {
2594 // Update our size.
2595 Die->setSize(OutOffset - Die->getOffset());
2596 return Die;
2597 }
2598
2599 // Recursively clone children.
2600 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2601 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002602 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002603 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002604 OutOffset = Clone->getOffset() + Clone->getSize();
2605 }
2606 }
2607
2608 // Account for the end of children marker.
2609 OutOffset += sizeof(int8_t);
2610 // Update our size.
2611 Die->setSize(OutOffset - Die->getOffset());
2612 return Die;
2613}
2614
Frederic Riss25440872015-03-13 23:30:31 +00002615/// \brief Patch the input object file relevant debug_ranges entries
2616/// and emit them in the output file. Update the relevant attributes
2617/// to point at the new entries.
2618void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2619 DWARFContext &OrigDwarf) const {
2620 DWARFDebugRangeList RangeList;
2621 const auto &FunctionRanges = Unit.getFunctionRanges();
2622 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2623 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2624 OrigDwarf.isLittleEndian(), AddressSize);
2625 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2626 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002627 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002628 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2629 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2630 // Ranges addresses are based on the unit's low_pc. Compute the
2631 // offset we need to apply to adapt to the the new unit's low_pc.
2632 int64_t UnitPcOffset = 0;
2633 if (OrigLowPc != -1ULL)
2634 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2635
2636 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002637 uint32_t Offset = RangeAttribute.get();
2638 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002639 RangeList.extract(RangeExtractor, &Offset);
2640 const auto &Entries = RangeList.getEntries();
Frederic Riss94546202015-08-31 05:09:32 +00002641 if (!Entries.empty()) {
2642 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
Frederic Riss25440872015-03-13 23:30:31 +00002643
Frederic Riss25440872015-03-13 23:30:31 +00002644 if (CurrRange == InvalidRange ||
Frederic Riss94546202015-08-31 05:09:32 +00002645 First.StartAddress + OrigLowPc < CurrRange.start() ||
2646 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2647 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2648 if (CurrRange == InvalidRange ||
2649 CurrRange.start() > First.StartAddress + OrigLowPc) {
2650 reportWarning("no mapping for range.");
2651 continue;
2652 }
Frederic Riss25440872015-03-13 23:30:31 +00002653 }
2654 }
2655
2656 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2657 AddressSize);
2658 }
2659}
2660
Frederic Riss563b1b02015-03-14 03:46:51 +00002661/// \brief Generate the debug_aranges entries for \p Unit and if the
2662/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2663/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002664/// FIXME: this could actually be done right in patchRangesForUnit,
2665/// but for the sake of initial bit-for-bit compatibility with legacy
2666/// dsymutil, we have to do it in a delayed pass.
2667void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002668 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002669 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002670 Attr->set(Streamer->getRangesSectionSize());
2671 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002672}
2673
Frederic Riss63786b02015-03-15 20:45:43 +00002674/// \brief Insert the new line info sequence \p Seq into the current
2675/// set of already linked line info \p Rows.
2676static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2677 std::vector<DWARFDebugLine::Row> &Rows) {
2678 if (Seq.empty())
2679 return;
2680
2681 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2682 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2683 Seq.clear();
2684 return;
2685 }
2686
2687 auto InsertPoint = std::lower_bound(
2688 Rows.begin(), Rows.end(), Seq.front(),
2689 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2690 return LHS.Address < RHS.Address;
2691 });
2692
2693 // FIXME: this only removes the unneeded end_sequence if the
2694 // sequences have been inserted in order. using a global sort like
2695 // described in patchLineTableForUnit() and delaying the end_sequene
2696 // elimination to emitLineTableForUnit() we can get rid of all of them.
2697 if (InsertPoint != Rows.end() &&
2698 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2699 *InsertPoint = Seq.front();
2700 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2701 } else {
2702 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2703 }
2704
2705 Seq.clear();
2706}
2707
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002708static void patchStmtList(DIE &Die, DIEInteger Offset) {
2709 for (auto &V : Die.values())
2710 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002711 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002712 return;
2713 }
2714
2715 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2716}
2717
Frederic Riss63786b02015-03-15 20:45:43 +00002718/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2719/// recreate a relocated version of these for the address ranges that
2720/// are present in the binary.
2721void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2722 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002723 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002724 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2725 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2726 if (StmtList == -1ULL)
2727 return;
2728
2729 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002730 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2731 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002732
2733 // Parse the original line info for the unit.
2734 DWARFDebugLine::LineTable LineTable;
2735 uint32_t StmtOffset = StmtList;
2736 StringRef LineData = OrigDwarf.getLineSection().Data;
2737 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2738 Unit.getOrigUnit().getAddressByteSize());
2739 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2740 &StmtOffset);
2741
2742 // This vector is the output line table.
2743 std::vector<DWARFDebugLine::Row> NewRows;
2744 NewRows.reserve(LineTable.Rows.size());
2745
2746 // Current sequence of rows being extracted, before being inserted
2747 // in NewRows.
2748 std::vector<DWARFDebugLine::Row> Seq;
2749 const auto &FunctionRanges = Unit.getFunctionRanges();
2750 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2751
2752 // FIXME: This logic is meant to generate exactly the same output as
2753 // Darwin's classic dsynutil. There is a nicer way to implement this
2754 // by simply putting all the relocated line info in NewRows and simply
2755 // sorting NewRows before passing it to emitLineTableForUnit. This
2756 // should be correct as sequences for a function should stay
2757 // together in the sorted output. There are a few corner cases that
2758 // look suspicious though, and that required to implement the logic
2759 // this way. Revisit that once initial validation is finished.
2760
2761 // Iterate over the object file line info and extract the sequences
2762 // that correspond to linked functions.
2763 for (auto &Row : LineTable.Rows) {
2764 // Check wether we stepped out of the range. The range is
2765 // half-open, but consider accept the end address of the range if
2766 // it is marked as end_sequence in the input (because in that
2767 // case, the relocation offset is accurate and that entry won't
2768 // serve as the start of another function).
2769 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2770 Row.Address > CurrRange.stop() ||
2771 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2772 // We just stepped out of a known range. Insert a end_sequence
2773 // corresponding to the end of the range.
2774 uint64_t StopAddress = CurrRange != InvalidRange
2775 ? CurrRange.stop() + CurrRange.value()
2776 : -1ULL;
2777 CurrRange = FunctionRanges.find(Row.Address);
2778 bool CurrRangeValid =
2779 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2780 if (!CurrRangeValid) {
2781 CurrRange = InvalidRange;
2782 if (StopAddress != -1ULL) {
2783 // Try harder by looking in the DebugMapObject function
2784 // ranges map. There are corner cases where this finds a
2785 // valid entry. It's unclear if this is right or wrong, but
2786 // for now do as dsymutil.
2787 // FIXME: Understand exactly what cases this addresses and
2788 // potentially remove it along with the Ranges map.
2789 auto Range = Ranges.lower_bound(Row.Address);
2790 if (Range != Ranges.begin() && Range != Ranges.end())
2791 --Range;
2792
2793 if (Range != Ranges.end() && Range->first <= Row.Address &&
2794 Range->second.first >= Row.Address) {
2795 StopAddress = Row.Address + Range->second.second;
2796 }
2797 }
2798 }
2799 if (StopAddress != -1ULL && !Seq.empty()) {
2800 // Insert end sequence row with the computed end address, but
2801 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00002802 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00002803 NextLine.Address = StopAddress;
2804 NextLine.EndSequence = 1;
2805 NextLine.PrologueEnd = 0;
2806 NextLine.BasicBlock = 0;
2807 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00002808 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00002809 insertLineSequence(Seq, NewRows);
2810 }
2811
2812 if (!CurrRangeValid)
2813 continue;
2814 }
2815
2816 // Ignore empty sequences.
2817 if (Row.EndSequence && Seq.empty())
2818 continue;
2819
2820 // Relocate row address and add it to the current sequence.
2821 Row.Address += CurrRange.value();
2822 Seq.emplace_back(Row);
2823
2824 if (Row.EndSequence)
2825 insertLineSequence(Seq, NewRows);
2826 }
2827
2828 // Finished extracting, now emit the line tables.
2829 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2830 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2831 // prologue over and that works because we act as both producer and
2832 // consumer. It would be nicer to have a real configurable line
2833 // table emitter.
2834 if (LineTable.Prologue.Version != 2 ||
2835 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00002836 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00002837 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00002838 else {
2839 MCDwarfLineTableParams Params;
2840 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
2841 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
2842 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
2843 Streamer->emitLineTableForUnit(Params,
2844 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00002845 LineTable.Prologue.MinInstLength, NewRows,
2846 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00002847 }
Frederic Riss63786b02015-03-15 20:45:43 +00002848}
2849
Frederic Rissbce93ff2015-03-16 02:05:10 +00002850void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2851 Streamer->emitPubNamesForUnit(Unit);
2852 Streamer->emitPubTypesForUnit(Unit);
2853}
2854
Frederic Riss5a642072015-06-05 23:06:11 +00002855/// \brief Read the frame info stored in the object, and emit the
2856/// patched frame descriptions for the linked binary.
2857///
2858/// This is actually pretty easy as the data of the CIEs and FDEs can
2859/// be considered as black boxes and moved as is. The only thing to do
2860/// is to patch the addresses in the headers.
2861void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2862 DWARFContext &OrigDwarf,
2863 unsigned AddrSize) {
2864 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2865 if (FrameData.empty())
2866 return;
2867
2868 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2869 uint32_t InputOffset = 0;
2870
2871 // Store the data of the CIEs defined in this object, keyed by their
2872 // offsets.
2873 DenseMap<uint32_t, StringRef> LocalCIES;
2874
2875 while (Data.isValidOffset(InputOffset)) {
2876 uint32_t EntryOffset = InputOffset;
2877 uint32_t InitialLength = Data.getU32(&InputOffset);
2878 if (InitialLength == 0xFFFFFFFF)
2879 return reportWarning("Dwarf64 bits no supported");
2880
2881 uint32_t CIEId = Data.getU32(&InputOffset);
2882 if (CIEId == 0xFFFFFFFF) {
2883 // This is a CIE, store it.
2884 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2885 LocalCIES[EntryOffset] = CIEData;
2886 // The -4 is to account for the CIEId we just read.
2887 InputOffset += InitialLength - 4;
2888 continue;
2889 }
2890
2891 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2892
2893 // Some compilers seem to emit frame info that doesn't start at
2894 // the function entry point, thus we can't just lookup the address
2895 // in the debug map. Use the linker's range map to see if the FDE
2896 // describes something that we can relocate.
2897 auto Range = Ranges.upper_bound(Loc);
2898 if (Range != Ranges.begin())
2899 --Range;
2900 if (Range == Ranges.end() || Range->first > Loc ||
2901 Range->second.first <= Loc) {
2902 // The +4 is to account for the size of the InitialLength field itself.
2903 InputOffset = EntryOffset + InitialLength + 4;
2904 continue;
2905 }
2906
2907 // This is an FDE, and we have a mapping.
2908 // Have we already emitted a corresponding CIE?
2909 StringRef CIEData = LocalCIES[CIEId];
2910 if (CIEData.empty())
2911 return reportWarning("Inconsistent debug_frame content. Dropping.");
2912
2913 // Look if we already emitted a CIE that corresponds to the
2914 // referenced one (the CIE data is the key of that lookup).
2915 auto IteratorInserted = EmittedCIEs.insert(
2916 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2917 // If there is no CIE yet for this ID, emit it.
2918 if (IteratorInserted.second ||
2919 // FIXME: dsymutil-classic only caches the last used CIE for
2920 // reuse. Mimic that behavior for now. Just removing that
2921 // second half of the condition and the LastCIEOffset variable
2922 // makes the code DTRT.
2923 LastCIEOffset != IteratorInserted.first->getValue()) {
2924 LastCIEOffset = Streamer->getFrameSectionSize();
2925 IteratorInserted.first->getValue() = LastCIEOffset;
2926 Streamer->emitCIE(CIEData);
2927 }
2928
2929 // Emit the FDE with updated address and CIE pointer.
2930 // (4 + AddrSize) is the size of the CIEId + initial_location
2931 // fields that will get reconstructed by emitFDE().
2932 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
2933 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
2934 Loc + Range->second.second,
2935 FrameData.substr(InputOffset, FDERemainingBytes));
2936 InputOffset += FDERemainingBytes;
2937 }
2938}
2939
Frederic Risseb85c8f2015-07-24 06:41:11 +00002940ErrorOr<const object::ObjectFile &>
2941DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
2942 const DebugMap &Map) {
2943 auto ErrOrObjs =
2944 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
Frederic Rissafeac302015-08-31 05:16:35 +00002945 if (std::error_code EC = ErrOrObjs.getError()) {
Frederic Risseb85c8f2015-07-24 06:41:11 +00002946 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
Frederic Rissafeac302015-08-31 05:16:35 +00002947 return EC;
2948 }
Frederic Risseb85c8f2015-07-24 06:41:11 +00002949 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
2950 if (std::error_code EC = ErrOrObj.getError())
2951 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
2952 return ErrOrObj;
2953}
2954
Frederic Rissd3455182015-01-28 18:27:01 +00002955bool DwarfLinker::link(const DebugMap &Map) {
2956
Frederic Rissc99ea202015-02-28 00:29:11 +00002957 if (!createStreamer(Map.getTriple(), OutputFilename))
2958 return false;
2959
Frederic Rissb8b43d52015-03-04 22:07:44 +00002960 // Size of the DIEs (and headers) generated for the linked output.
2961 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002962 // A unique ID that identifies each compile unit.
2963 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002964 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002965 CurrentDebugObject = Obj.get();
2966
Frederic Rissb9818322015-02-28 00:29:07 +00002967 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002968 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00002969 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
2970 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00002971 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00002972
Frederic Riss1036e642015-02-13 23:18:22 +00002973 // Look for relocations that correspond to debug map entries.
2974 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002975 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002976 outs() << "No valid relocations found. Skipping.\n";
2977 continue;
2978 }
2979
Frederic Riss563cba62015-01-28 22:15:14 +00002980 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002981 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002982 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002983
Frederic Riss563cba62015-01-28 22:15:14 +00002984 // In a first phase, just read in the debug info and store the DIE
2985 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002986 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002987 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002988 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002989 outs() << "Input compilation unit:";
2990 CUDie->dump(outs(), CU.get(), 0);
2991 }
Frederic Riss1c650942015-07-21 22:41:43 +00002992 Units.emplace_back(*CU, UnitID++, !Options.NoODR);
2993 gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
2994 StringPool, ODRContexts);
Frederic Rissd3455182015-01-28 18:27:01 +00002995 }
Frederic Riss563cba62015-01-28 22:15:14 +00002996
Frederic Riss84c09a52015-02-13 23:18:34 +00002997 // Then mark all the DIEs that need to be present in the linked
2998 // output and collect some information about them. Note that this
2999 // loop can not be merged with the previous one becaue cross-cu
3000 // references require the ParentIdx to be setup for every CU in
3001 // the object file before calling this.
3002 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003003 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00003004 CurrentUnit, 0);
3005
Frederic Riss23e20e92015-03-07 01:25:09 +00003006 // The calls to applyValidRelocs inside cloneDIE will walk the
3007 // reloc array again (in the same way findValidRelocsInDebugInfo()
3008 // did). We need to reset the NextValidReloc index to the beginning.
3009 NextValidReloc = 0;
3010
Frederic Rissb8b43d52015-03-04 22:07:44 +00003011 // Construct the output DIE tree by cloning the DIEs we chose to
3012 // keep above. If there are no valid relocs, then there's nothing
3013 // to clone/emit.
3014 if (!ValidRelocs.empty())
3015 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003016 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00003017 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00003018 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
3019 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00003020 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00003021 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00003022 if (Options.NoOutput)
3023 continue;
3024 // FIXME: for compatibility with the classic dsymutil, we emit
3025 // an empty line table for the unit, even if the unit doesn't
3026 // actually exist in the DIE tree.
3027 patchLineTableForUnit(CurrentUnit, DwarfContext);
3028 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00003029 continue;
3030 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00003031 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00003032 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00003033 }
3034
3035 // Emit all the compile unit's debug information.
3036 if (!ValidRelocs.empty() && !Options.NoOutput)
3037 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00003038 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00003039 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00003040 Streamer->emitCompileUnitHeader(CurrentUnit);
3041 if (!CurrentUnit.getOutputUnitDIE())
3042 continue;
3043 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3044 }
3045
Frederic Riss5a642072015-06-05 23:06:11 +00003046 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
3047 patchFrameInfoForObject(*Obj, DwarfContext,
3048 Units[0].getOrigUnit().getAddressByteSize());
3049
Frederic Riss563cba62015-01-28 22:15:14 +00003050 // Clean-up before starting working on the next object.
3051 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003052 }
3053
Frederic Rissb8b43d52015-03-04 22:07:44 +00003054 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003055 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003056 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003057 Streamer->emitStrings(StringPool);
3058 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003059
Frederic Riss5f369032015-08-26 06:41:57 +00003060 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00003061}
3062}
Frederic Rissd3455182015-01-28 18:27:01 +00003063
Frederic Riss30711fb2015-08-26 05:09:52 +00003064/// \brief Get the offset of string \p S in the string table. This
3065/// can insert a new element or return the offset of a preexisitng
3066/// one.
3067uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3068 if (S.empty() && !Strings.empty())
3069 return 0;
3070
3071 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3072 MapTy::iterator It;
3073 bool Inserted;
3074
3075 // A non-empty string can't be at offset 0, so if we have an entry
3076 // with a 0 offset, it must be a previously interned string.
3077 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3078 if (Inserted || It->getValue().first == 0) {
3079 // Set offset and chain at the end of the entries list.
3080 It->getValue().first = CurrentEndOffset;
3081 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3082 Last->getValue().second = &*It;
3083 Last = &*It;
3084 }
3085 return It->getValue().first;
3086}
3087
3088/// \brief Put \p S into the StringMap so that it gets permanent
3089/// storage, but do not actually link it in the chain of elements
3090/// that go into the output section. A latter call to
3091/// getStringOffset() with the same string will chain it though.
3092StringRef NonRelocatableStringpool::internString(StringRef S) {
3093 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3094 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3095 return InsertResult.first->getKey();
3096}
3097
Frederic Riss65e145c2015-08-26 05:09:55 +00003098void warn(const Twine &Warning, const Twine &Context) {
3099 errs() << Twine("while processing ") + Context + ":\n";
3100 errs() << Twine("warning: ") + Warning + "\n";
3101}
3102
3103bool error(const Twine &Error, const Twine &Context) {
3104 errs() << Twine("while processing ") + Context + ":\n";
3105 errs() << Twine("error: ") + Error + "\n";
3106 return false;
3107}
3108
Frederic Rissb9818322015-02-28 00:29:07 +00003109bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3110 const LinkOptions &Options) {
3111 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003112 return Linker.link(DM);
3113}
3114}
Frederic Riss231f7142014-12-12 17:31:24 +00003115}