blob: 0be12375b2658ba3a5ac58e7f4722b412a36e495 [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 Rissc99ea202015-02-28 00:29:11 +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
620bool DwarfStreamer::finish() {
621 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.
691 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
692 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 Riss31da3242015-03-11 18:45:52 +00001209 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1210 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1211
Frederic Rissbce93ff2015-03-16 02:05:10 +00001212 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1213 bool IsDeclaration; ///< Is this DIE only a declaration?
1214
1215 AttributesInfo()
1216 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1217 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1218 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001219 };
1220
Frederic Rissb8b43d52015-03-04 22:07:44 +00001221 /// \brief Helper for cloneDIE.
1222 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1223 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001224 const AttributeSpec AttrSpec, unsigned AttrSize,
1225 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001226
1227 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001228 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1229 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001230
1231 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001232 unsigned
1233 cloneDieReferenceAttribute(DIE &Die,
1234 const DWARFDebugInfoEntryMinimal &InputDIE,
1235 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001236 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001237
1238 /// \brief Helper for cloneDIE.
1239 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1240 const DWARFFormValue &Val, unsigned AttrSize);
1241
1242 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001243 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1244 const DWARFFormValue &Val,
1245 const CompileUnit &Unit, AttributesInfo &Info);
1246
1247 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001248 unsigned cloneScalarAttribute(DIE &Die,
1249 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001250 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001251 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001252 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001253
Frederic Riss23e20e92015-03-07 01:25:09 +00001254 /// \brief Helper for cloneDIE.
1255 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1256 bool isLittleEndian);
1257
Frederic Rissb8b43d52015-03-04 22:07:44 +00001258 /// \brief Assign an abbreviation number to \p Abbrev
1259 void AssignAbbrev(DIEAbbrev &Abbrev);
1260
1261 /// \brief FoldingSet that uniques the abbreviations.
1262 FoldingSet<DIEAbbrev> AbbreviationsSet;
1263 /// \brief Storage for the unique Abbreviations.
1264 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1265 /// be changed to a vecot of unique_ptrs.
1266 std::vector<DIEAbbrev *> Abbreviations;
1267
Frederic Riss25440872015-03-13 23:30:31 +00001268 /// \brief Compute and emit debug_ranges section for \p Unit, and
1269 /// patch the attributes referencing it.
1270 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1271
1272 /// \brief Generate and emit the DW_AT_ranges attribute for a
1273 /// compile_unit if it had one.
1274 void generateUnitRanges(CompileUnit &Unit) const;
1275
Frederic Riss63786b02015-03-15 20:45:43 +00001276 /// \brief Extract the line tables fromt he original dwarf, extract
1277 /// the relevant parts according to the linked function ranges and
1278 /// emit the result in the debug_line section.
1279 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1280
Frederic Rissbce93ff2015-03-16 02:05:10 +00001281 /// \brief Emit the accelerator entries for \p Unit.
1282 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1283
Frederic Riss5a642072015-06-05 23:06:11 +00001284 /// \brief Patch the frame info for an object file and emit it.
1285 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1286 unsigned AddressSize);
1287
Frederic Rissb8b43d52015-03-04 22:07:44 +00001288 /// \brief DIELoc objects that need to be destructed (but not freed!).
1289 std::vector<DIELoc *> DIELocs;
1290 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1291 std::vector<DIEBlock *> DIEBlocks;
1292 /// \brief Allocator used for all the DIEValue objects.
1293 BumpPtrAllocator DIEAlloc;
1294 /// @}
1295
Frederic Riss1c650942015-07-21 22:41:43 +00001296 /// ODR Contexts for that link.
1297 DeclContextTree ODRContexts;
1298
Frederic Riss1b9da422015-02-13 23:18:29 +00001299 /// \defgroup Helpers Various helper methods.
1300 ///
1301 /// @{
1302 const DWARFDebugInfoEntryMinimal *
Frederic Riss1c650942015-07-21 22:41:43 +00001303 resolveDIEReference(const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001304 const DWARFDebugInfoEntryMinimal &DIE,
1305 CompileUnit *&ReferencedCU);
1306
1307 CompileUnit *getUnitForOffset(unsigned Offset);
1308
Frederic Rissbce93ff2015-03-16 02:05:10 +00001309 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1310 AttributesInfo &Info);
1311
Frederic Riss1b9da422015-02-13 23:18:29 +00001312 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001313 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001314
1315 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001316
1317 /// \brief Attempt to load a debug object from disk.
1318 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1319 DebugMapObject &Obj,
1320 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001321 /// @}
1322
Frederic Riss563cba62015-01-28 22:15:14 +00001323private:
Frederic Rissd3455182015-01-28 18:27:01 +00001324 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001325 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001326 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001327 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001328
1329 /// The units of the current debug map object.
1330 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001331
1332 /// The debug map object curently under consideration.
1333 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001334
1335 /// \brief The Dwarf string pool
1336 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001337
1338 /// \brief This map is keyed by the entry PC of functions in that
1339 /// debug object and the associated value is a pair storing the
1340 /// corresponding end PC and the offset to apply to get the linked
1341 /// address.
1342 ///
1343 /// See startDebugObject() for a more complete description of its use.
1344 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001345
1346 /// \brief The CIEs that have been emitted in the output
1347 /// section. The actual CIE data serves a the key to this StringMap,
1348 /// this takes care of comparing the semantics of CIEs defined in
1349 /// different object files.
1350 StringMap<uint32_t> EmittedCIEs;
1351
1352 /// Offset of the last CIE that has been emitted in the output
1353 /// debug_frame section.
1354 uint32_t LastCIEOffset;
Frederic Rissd3455182015-01-28 18:27:01 +00001355};
1356
Frederic Riss1b9da422015-02-13 23:18:29 +00001357/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1358/// returning our CompileUnit object instead.
1359CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1360 auto CU =
1361 std::upper_bound(Units.begin(), Units.end(), Offset,
1362 [](uint32_t LHS, const CompileUnit &RHS) {
1363 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1364 });
1365 return CU != Units.end() ? &*CU : nullptr;
1366}
1367
1368/// \brief Resolve the DIE attribute reference that has been
1369/// extracted in \p RefValue. The resulting DIE migh be in another
1370/// CompileUnit which is stored into \p ReferencedCU.
1371/// \returns null if resolving fails for any reason.
1372const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
Frederic Riss1c650942015-07-21 22:41:43 +00001373 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001374 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1375 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1376 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1377
1378 if ((RefCU = getUnitForOffset(RefOffset)))
1379 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1380 return RefDie;
1381
1382 reportWarning("could not find referenced DIE", &Unit, &DIE);
1383 return nullptr;
1384}
1385
Frederic Riss1c650942015-07-21 22:41:43 +00001386/// \returns whether the passed \a Attr type might contain a DIE
1387/// reference suitable for ODR uniquing.
1388static bool isODRAttribute(uint16_t Attr) {
1389 switch (Attr) {
1390 default:
1391 return false;
1392 case dwarf::DW_AT_type:
1393 case dwarf::DW_AT_containing_type:
1394 case dwarf::DW_AT_specification:
1395 case dwarf::DW_AT_abstract_origin:
1396 case dwarf::DW_AT_import:
1397 return true;
1398 }
1399 llvm_unreachable("Improper attribute.");
1400}
1401
1402/// Set the last DIE/CU a context was seen in and, possibly invalidate
1403/// the context if it is ambiguous.
1404///
1405/// In the current implementation, we don't handle overloaded
1406/// functions well, because the argument types are not taken into
1407/// account when computing the DeclContext tree.
1408///
1409/// Some of this is mitigated byt using mangled names that do contain
1410/// the arguments types, but sometimes (eg. with function templates)
1411/// we don't have that. In that case, just do not unique anything that
1412/// refers to the contexts we are not able to distinguish.
1413///
1414/// If a context that is not a namespace appears twice in the same CU,
1415/// we know it is ambiguous. Make it invalid.
1416bool DeclContext::setLastSeenDIE(CompileUnit &U,
1417 const DWARFDebugInfoEntryMinimal *Die) {
1418 if (LastSeenCompileUnitID == U.getUniqueID()) {
1419 DWARFUnit &OrigUnit = U.getOrigUnit();
1420 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1421 U.getInfo(FirstIdx).Ctxt = nullptr;
1422 return false;
1423 }
1424
1425 LastSeenCompileUnitID = U.getUniqueID();
1426 LastSeenDIE = Die;
1427 return true;
1428}
1429
1430/// Get the child context of \a Context corresponding to \a DIE.
1431///
1432/// \returns the child context or null if we shouldn't track children
1433/// contexts. It also returns an additional bit meaning 'invalid'. An
1434/// invalid context means it shouldn't be considered for uniquing, but
1435/// its not returning null, because some children of that context
1436/// might be uniquing candidates.
1437/// FIXME: this is for dsymutil-classic compatibility, I don't think
1438/// it buys us much.
1439PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1440 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1441 NonRelocatableStringpool &StringPool) {
1442 unsigned Tag = DIE->getTag();
1443
1444 // FIXME: dsymutil-classic compat: We should bail out here if we
1445 // have a specification or an abstract_origin. We will get the
1446 // parent context wrong here.
1447
1448 switch (Tag) {
1449 default:
1450 // By default stop gathering child contexts.
1451 return PointerIntPair<DeclContext *, 1>(nullptr);
1452 case dwarf::DW_TAG_compile_unit:
1453 // FIXME: Add support for DW_TAG_module.
1454 return PointerIntPair<DeclContext *, 1>(&Context);
1455 case dwarf::DW_TAG_subprogram:
1456 // Do not unique anything inside CU local functions.
1457 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1458 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1459 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1460 dwarf::DW_AT_external, 0))
1461 return PointerIntPair<DeclContext *, 1>(nullptr);
1462 // Fallthrough
1463 case dwarf::DW_TAG_member:
1464 case dwarf::DW_TAG_namespace:
1465 case dwarf::DW_TAG_structure_type:
1466 case dwarf::DW_TAG_class_type:
1467 case dwarf::DW_TAG_union_type:
1468 case dwarf::DW_TAG_enumeration_type:
1469 case dwarf::DW_TAG_typedef:
1470 // Artificial things might be ambiguous, because they might be
1471 // created on demand. For example implicitely defined constructors
1472 // are ambiguous because of the way we identify contexts, and they
1473 // won't be generated everytime everywhere.
1474 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1475 dwarf::DW_AT_artificial, 0))
1476 return PointerIntPair<DeclContext *, 1>(nullptr);
1477 break;
1478 }
1479
1480 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1481 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1482 StringRef NameRef;
1483 StringRef ShortNameRef;
1484 StringRef FileRef;
1485
1486 if (Name)
1487 NameRef = StringPool.internString(Name);
1488 else if (Tag == dwarf::DW_TAG_namespace)
1489 // FIXME: For dsymutil-classic compatibility. I think uniquing
1490 // within anonymous namespaces is wrong. There is no ODR guarantee
1491 // there.
1492 NameRef = StringPool.internString("(anonymous namespace)");
1493
1494 if (ShortName && ShortName != Name)
1495 ShortNameRef = StringPool.internString(ShortName);
1496 else
1497 ShortNameRef = NameRef;
1498
1499 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1500 Tag != dwarf::DW_TAG_union_type &&
1501 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1502 return PointerIntPair<DeclContext *, 1>(nullptr);
1503
1504 std::string File;
1505 unsigned Line = 0;
1506 unsigned ByteSize = 0;
1507
1508 // Gather some discriminating data about the DeclContext we will be
1509 // creating: File, line number and byte size. This shouldn't be
1510 // necessary, because the ODR is just about names, but given that we
1511 // do some approximations with overloaded functions and anonymous
1512 // namespaces, use these additional data points to make the process safer.
1513 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1514 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1515 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1516 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1517 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1518 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1519 &U.getOrigUnit())) {
1520 // FIXME: dsymutil-classic compatibility. I'd rather not
1521 // unique anything in anonymous namespaces, but if we do, then
1522 // verify that the file and line correspond.
1523 if (!Name && Tag == dwarf::DW_TAG_namespace)
1524 FileNum = 1;
1525
1526 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1527 // instead of "" would allow more uniquing, but for now, do
1528 // it this way to match dsymutil-classic.
1529 if (LT->getFileNameByIndex(
1530 FileNum, "",
1531 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1532 File)) {
1533 Line = DIE->getAttributeValueAsUnsignedConstant(
1534 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1535#ifdef HAVE_REALPATH
1536 // Cache the resolved paths, because calling realpath is expansive.
1537 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1538 File = ResolvedPath;
1539 } else {
1540 char RealPath[PATH_MAX + 1];
1541 RealPath[PATH_MAX] = 0;
1542 if (::realpath(File.c_str(), RealPath))
1543 File = RealPath;
1544 U.setResolvedPath(FileNum, File);
1545 }
1546#endif
1547 FileRef = StringPool.internString(File);
1548 }
1549 }
1550 }
1551 }
1552
1553 if (!Line && NameRef.empty())
1554 return PointerIntPair<DeclContext *, 1>(nullptr);
1555
1556 // FIXME: dsymutil-classic compat won't unique the same type
1557 // presented once as a struct and once as a class. Use the Tag in
1558 // the fully qualified name hash to get the same effect.
1559 // We hash NameRef, which is the mangled name, in order to get most
1560 // overloaded functions resolvec correctly.
1561 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1562
1563 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1564 // use the filename.
1565 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1566 Hash = hash_combine(Hash, FileRef);
1567
1568 // Now look if this context already exists.
1569 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1570 auto ContextIter = Contexts.find(&Key);
1571
1572 if (ContextIter == Contexts.end()) {
1573 // The context wasn't found.
1574 bool Inserted;
1575 DeclContext *NewContext =
1576 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1577 Context, DIE, U.getUniqueID());
1578 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1579 assert(Inserted && "Failed to insert DeclContext");
1580 (void)Inserted;
1581 } else if (Tag != dwarf::DW_TAG_namespace &&
1582 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1583 // The context was found, but it is ambiguous with another context
1584 // in the same file. Mark it invalid.
1585 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1586 }
1587
1588 assert(ContextIter != Contexts.end());
1589 // FIXME: dsymutil-classic compatibility. Union types aren't
1590 // uniques, but their children might be.
1591 if ((Tag == dwarf::DW_TAG_subprogram &&
1592 Context.getTag() != dwarf::DW_TAG_structure_type &&
1593 Context.getTag() != dwarf::DW_TAG_class_type) ||
1594 (Tag == dwarf::DW_TAG_union_type))
1595 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1596
1597 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1598}
1599
Frederic Rissbce93ff2015-03-16 02:05:10 +00001600/// \brief Get the potential name and mangled name for the entity
1601/// described by \p Die and store them in \Info if they are not
1602/// already there.
1603/// \returns is a name was found.
1604bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1605 DWARFUnit &U, AttributesInfo &Info) {
1606 // FIXME: a bit wastefull as the first getName might return the
1607 // short name.
1608 if (!Info.MangledName &&
1609 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1610 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1611
1612 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1613 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1614
1615 return Info.Name || Info.MangledName;
1616}
1617
Frederic Riss1b9da422015-02-13 23:18:29 +00001618/// \brief Report a warning to the user, optionaly including
1619/// information about a specific \p DIE related to the warning.
1620void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001621 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001622 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001623 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001624 Context = CurrentDebugObject->getObjectFilename();
1625 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001626
Frederic Rissb9818322015-02-28 00:29:07 +00001627 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001628 return;
1629
1630 errs() << " in DIE:\n";
1631 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1632 6 /* Indent */);
1633}
1634
Frederic Rissc99ea202015-02-28 00:29:11 +00001635bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1636 if (Options.NoOutput)
1637 return true;
1638
Frederic Rissb52cf522015-02-28 00:42:37 +00001639 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001640 return Streamer->init(TheTriple, OutputFilename);
1641}
1642
Frederic Riss563cba62015-01-28 22:15:14 +00001643/// \brief Recursive helper to gather the child->parent relationships in the
1644/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001645static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
Frederic Riss1c650942015-07-21 22:41:43 +00001646 unsigned ParentIdx, CompileUnit &CU,
1647 DeclContext *CurrentDeclContext,
1648 NonRelocatableStringpool &StringPool,
1649 DeclContextTree &Contexts) {
Frederic Riss563cba62015-01-28 22:15:14 +00001650 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001651 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1652
1653 Info.ParentIdx = ParentIdx;
1654 if (CU.hasODR()) {
1655 if (CurrentDeclContext) {
1656 auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1657 DIE, CU, StringPool);
1658 CurrentDeclContext = PtrInvalidPair.getPointer();
1659 Info.Ctxt =
1660 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1661 } else
1662 Info.Ctxt = CurrentDeclContext = nullptr;
1663 }
Frederic Riss563cba62015-01-28 22:15:14 +00001664
1665 if (DIE->hasChildren())
1666 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1667 Child = Child->getSibling())
Frederic Riss1c650942015-07-21 22:41:43 +00001668 gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1669 Contexts);
Frederic Riss563cba62015-01-28 22:15:14 +00001670}
1671
Frederic Riss84c09a52015-02-13 23:18:34 +00001672static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1673 switch (Tag) {
1674 default:
1675 return false;
1676 case dwarf::DW_TAG_subprogram:
1677 case dwarf::DW_TAG_lexical_block:
1678 case dwarf::DW_TAG_subroutine_type:
1679 case dwarf::DW_TAG_structure_type:
1680 case dwarf::DW_TAG_class_type:
1681 case dwarf::DW_TAG_union_type:
1682 return true;
1683 }
1684 llvm_unreachable("Invalid Tag");
1685}
1686
Frederic Riss1c650942015-07-21 22:41:43 +00001687static unsigned getRefAddrSize(const DWARFUnit &U) {
1688 if (U.getVersion() == 2)
1689 return U.getAddressByteSize();
1690 return 4;
1691}
1692
Frederic Riss63786b02015-03-15 20:45:43 +00001693void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001694 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001695 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001696 // Iterate over the debug map entries and put all the ones that are
1697 // functions (because they have a size) into the Ranges map. This
1698 // map is very similar to the FunctionRanges that are stored in each
1699 // unit, with 2 notable differences:
1700 // - obviously this one is global, while the other ones are per-unit.
1701 // - this one contains not only the functions described in the DIE
1702 // tree, but also the ones that are only in the debug map.
1703 // The latter information is required to reproduce dsymutil's logic
1704 // while linking line tables. The cases where this information
1705 // matters look like bugs that need to be investigated, but for now
1706 // we need to reproduce dsymutil's behavior.
1707 // FIXME: Once we understood exactly if that information is needed,
1708 // maybe totally remove this (or try to use it to do a real
1709 // -gline-tables-only on Darwin.
1710 for (const auto &Entry : Obj.symbols()) {
1711 const auto &Mapping = Entry.getValue();
1712 if (Mapping.Size)
1713 Ranges[Mapping.ObjectAddress] = std::make_pair(
1714 Mapping.ObjectAddress + Mapping.Size,
1715 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1716 }
Frederic Riss563cba62015-01-28 22:15:14 +00001717}
1718
Frederic Riss1036e642015-02-13 23:18:22 +00001719void DwarfLinker::endDebugObject() {
1720 Units.clear();
1721 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001722 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001723
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001724 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1725 (*I)->~DIEBlock();
1726 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1727 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001728
1729 DIEBlocks.clear();
1730 DIELocs.clear();
1731 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001732}
1733
1734/// \brief Iterate over the relocations of the given \p Section and
1735/// store the ones that correspond to debug map entries into the
1736/// ValidRelocs array.
1737void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1738 const object::MachOObjectFile &Obj,
1739 const DebugMapObject &DMO) {
1740 StringRef Contents;
1741 Section.getContents(Contents);
1742 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1743
1744 for (const object::RelocationRef &Reloc : Section.relocations()) {
1745 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1746 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1747 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001748 uint64_t Offset64 = Reloc.getOffset();
1749 if ((RelocSize != 4 && RelocSize != 8)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001750 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001751 continue;
1752 }
1753 uint32_t Offset = Offset64;
1754 // Mach-o uses REL relocations, the addend is at the relocation offset.
1755 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1756
1757 auto Sym = Reloc.getSymbol();
1758 if (Sym != Obj.symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001759 ErrorOr<StringRef> SymbolName = Sym->getName();
1760 if (!SymbolName) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001761 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001762 continue;
1763 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001764 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001765 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1766 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1767 // Do not store the addend. The addend was the address of the
1768 // symbol in the object file, the address in the binary that is
1769 // stored in the debug map doesn't need to be offseted.
1770 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1771 }
1772 }
1773}
1774
1775/// \brief Dispatch the valid relocation finding logic to the
1776/// appropriate handler depending on the object file format.
1777bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1778 const object::ObjectFile &Obj,
1779 const DebugMapObject &DMO) {
1780 // Dispatch to the right handler depending on the file type.
1781 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1782 findValidRelocsMachO(Section, *MachOObj, DMO);
1783 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001784 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001785
1786 if (ValidRelocs.empty())
1787 return false;
1788
1789 // Sort the relocations by offset. We will walk the DIEs linearly in
1790 // the file, this allows us to just keep an index in the relocation
1791 // array that we advance during our walk, rather than resorting to
1792 // some associative container. See DwarfLinker::NextValidReloc.
1793 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1794 return true;
1795}
1796
1797/// \brief Look for relocations in the debug_info section that match
1798/// entries in the debug map. These relocations will drive the Dwarf
1799/// link by indicating which DIEs refer to symbols present in the
1800/// linked binary.
1801/// \returns wether there are any valid relocations in the debug info.
1802bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1803 const DebugMapObject &DMO) {
1804 // Find the debug_info section.
1805 for (const object::SectionRef &Section : Obj.sections()) {
1806 StringRef SectionName;
1807 Section.getName(SectionName);
1808 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1809 if (SectionName != "debug_info")
1810 continue;
1811 return findValidRelocs(Section, Obj, DMO);
1812 }
1813 return false;
1814}
Frederic Riss563cba62015-01-28 22:15:14 +00001815
Frederic Riss84c09a52015-02-13 23:18:34 +00001816/// \brief Checks that there is a relocation against an actual debug
1817/// map entry between \p StartOffset and \p NextOffset.
1818///
1819/// This function must be called with offsets in strictly ascending
1820/// order because it never looks back at relocations it already 'went past'.
1821/// \returns true and sets Info.InDebugMap if it is the case.
1822bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1823 CompileUnit::DIEInfo &Info) {
1824 assert(NextValidReloc == 0 ||
1825 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1826 if (NextValidReloc >= ValidRelocs.size())
1827 return false;
1828
1829 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1830
1831 // We might need to skip some relocs that we didn't consider. For
1832 // example the high_pc of a discarded DIE might contain a reloc that
1833 // is in the list because it actually corresponds to the start of a
1834 // function that is in the debug map.
1835 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1836 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1837
1838 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1839 return false;
1840
1841 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001842 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissb9818322015-02-28 00:29:07 +00001843 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001844 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1845 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001846 uint64_t(Mapping.ObjectAddress),
1847 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001848
Frederic Rissf37964c2015-06-05 20:27:07 +00001849 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1850 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001851 Info.InDebugMap = true;
1852 return true;
1853}
1854
1855/// \brief Get the starting and ending (exclusive) offset for the
1856/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1857/// supposed to point to the position of the first attribute described
1858/// by \p Abbrev.
1859/// \return [StartOffset, EndOffset) as a pair.
1860static std::pair<uint32_t, uint32_t>
1861getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1862 unsigned Offset, const DWARFUnit &Unit) {
1863 DataExtractor Data = Unit.getDebugInfoExtractor();
1864
1865 for (unsigned i = 0; i < Idx; ++i)
1866 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1867
1868 uint32_t End = Offset;
1869 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1870
1871 return std::make_pair(Offset, End);
1872}
1873
1874/// \brief Check if a variable describing DIE should be kept.
1875/// \returns updated TraversalFlags.
1876unsigned DwarfLinker::shouldKeepVariableDIE(
1877 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1878 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1879 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1880
1881 // Global variables with constant value can always be kept.
1882 if (!(Flags & TF_InFunctionScope) &&
1883 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1884 MyInfo.InDebugMap = true;
1885 return Flags | TF_Keep;
1886 }
1887
1888 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1889 if (LocationIdx == -1U)
1890 return Flags;
1891
1892 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1893 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1894 uint32_t LocationOffset, LocationEndOffset;
1895 std::tie(LocationOffset, LocationEndOffset) =
1896 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1897
1898 // See if there is a relocation to a valid debug map entry inside
1899 // this variable's location. The order is important here. We want to
1900 // always check in the variable has a valid relocation, so that the
1901 // DIEInfo is filled. However, we don't want a static variable in a
1902 // function to force us to keep the enclosing function.
1903 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1904 (Flags & TF_InFunctionScope))
1905 return Flags;
1906
Frederic Rissb9818322015-02-28 00:29:07 +00001907 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001908 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1909
1910 return Flags | TF_Keep;
1911}
1912
1913/// \brief Check if a function describing DIE should be kept.
1914/// \returns updated TraversalFlags.
1915unsigned DwarfLinker::shouldKeepSubprogramDIE(
1916 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1917 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1918 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1919
1920 Flags |= TF_InFunctionScope;
1921
1922 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1923 if (LowPcIdx == -1U)
1924 return Flags;
1925
1926 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1927 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1928 uint32_t LowPcOffset, LowPcEndOffset;
1929 std::tie(LowPcOffset, LowPcEndOffset) =
1930 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1931
1932 uint64_t LowPc =
1933 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1934 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1935 if (LowPc == -1ULL ||
1936 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1937 return Flags;
1938
Frederic Rissb9818322015-02-28 00:29:07 +00001939 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001940 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1941
Frederic Riss1af75f72015-03-12 18:45:10 +00001942 Flags |= TF_Keep;
1943
1944 DWARFFormValue HighPcValue;
1945 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1946 reportWarning("Function without high_pc. Range will be discarded.\n",
1947 &OrigUnit, &DIE);
1948 return Flags;
1949 }
1950
1951 uint64_t HighPc;
1952 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1953 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1954 } else {
1955 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1956 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1957 }
1958
Frederic Riss63786b02015-03-15 20:45:43 +00001959 // Replace the debug map range with a more accurate one.
1960 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001961 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1962 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001963}
1964
1965/// \brief Check if a DIE should be kept.
1966/// \returns updated TraversalFlags.
1967unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1968 CompileUnit &Unit,
1969 CompileUnit::DIEInfo &MyInfo,
1970 unsigned Flags) {
1971 switch (DIE.getTag()) {
1972 case dwarf::DW_TAG_constant:
1973 case dwarf::DW_TAG_variable:
1974 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1975 case dwarf::DW_TAG_subprogram:
1976 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1977 case dwarf::DW_TAG_module:
1978 case dwarf::DW_TAG_imported_module:
1979 case dwarf::DW_TAG_imported_declaration:
1980 case dwarf::DW_TAG_imported_unit:
1981 // We always want to keep these.
1982 return Flags | TF_Keep;
1983 }
1984
1985 return Flags;
1986}
1987
Frederic Riss84c09a52015-02-13 23:18:34 +00001988/// \brief Mark the passed DIE as well as all the ones it depends on
1989/// as kept.
1990///
1991/// This function is called by lookForDIEsToKeep on DIEs that are
1992/// newly discovered to be needed in the link. It recursively calls
1993/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1994/// TraversalFlags to inform it that it's not doing the primary DIE
1995/// tree walk.
1996void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1997 CompileUnit::DIEInfo &MyInfo,
1998 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00001999 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002000 const DWARFUnit &Unit = CU.getOrigUnit();
2001 MyInfo.Keep = true;
2002
2003 // First mark all the parent chain as kept.
2004 unsigned AncestorIdx = MyInfo.ParentIdx;
2005 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002006 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Frederic Riss84c09a52015-02-13 23:18:34 +00002007 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002008 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002009 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2010 }
2011
2012 // Then we need to mark all the DIEs referenced by this DIE's
2013 // attributes as kept.
2014 DataExtractor Data = Unit.getDebugInfoExtractor();
2015 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2016 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2017
2018 // Mark all DIEs referenced through atttributes as kept.
2019 for (const auto &AttrSpec : Abbrev->attributes()) {
2020 DWARFFormValue Val(AttrSpec.Form);
2021
2022 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2023 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2024 continue;
2025 }
2026
2027 Val.extractValue(Data, &Offset, &Unit);
2028 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002029 if (const auto *RefDIE =
2030 resolveDIEReference(Val, Unit, DIE, ReferencedCU)) {
2031 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2032 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2033 // If the referenced DIE has a DeclContext that has already been
2034 // emitted, then do not keep the one in this CU. We'll link to
2035 // the canonical DIE in cloneDieReferenceAttribute.
2036 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2037 // be necessary and could be advantageously replaced by
2038 // ReferencedCU->hasODR() && CU.hasODR().
2039 // FIXME: compatibility with dsymutil-classic. There is no
2040 // reason not to unique ref_addr references.
2041 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2042 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2043 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2044 continue;
2045
2046 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Frederic Riss84c09a52015-02-13 23:18:34 +00002047 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002048 TF_Keep | TF_DependencyWalk | ODRFlag);
2049 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002050 }
2051}
2052
2053/// \brief Recursively walk the \p DIE tree and look for DIEs to
2054/// keep. Store that information in \p CU's DIEInfo.
2055///
2056/// This function is the entry point of the DIE selection
2057/// algorithm. It is expected to walk the DIE tree in file order and
2058/// (though the mediation of its helper) call hasValidRelocation() on
2059/// each DIE that might be a 'root DIE' (See DwarfLinker class
2060/// comment).
2061/// While walking the dependencies of root DIEs, this function is
2062/// also called, but during these dependency walks the file order is
2063/// not respected. The TF_DependencyWalk flag tells us which kind of
2064/// traversal we are currently doing.
2065void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
2066 const DebugMapObject &DMO, CompileUnit &CU,
2067 unsigned Flags) {
2068 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
2069 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2070 bool AlreadyKept = MyInfo.Keep;
2071
2072 // If the Keep flag is set, we are marking a required DIE's
2073 // dependencies. If our target is already marked as kept, we're all
2074 // set.
2075 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2076 return;
2077
2078 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2079 // because it would screw up the relocation finding logic.
2080 if (!(Flags & TF_DependencyWalk))
2081 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
2082
2083 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002084 if (!AlreadyKept && (Flags & TF_Keep)) {
2085 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2086 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, UseOdr);
2087 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002088 // The TF_ParentWalk flag tells us that we are currently walking up
2089 // the parent chain of a required DIE, and we don't want to mark all
2090 // the children of the parents as kept (consider for example a
2091 // DW_TAG_namespace node in the parent chain). There are however a
2092 // set of DIE types for which we want to ignore that directive and still
2093 // walk their children.
2094 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
2095 Flags &= ~TF_ParentWalk;
2096
2097 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
2098 return;
2099
2100 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
2101 Child = Child->getSibling())
2102 lookForDIEsToKeep(*Child, DMO, CU, Flags);
2103}
2104
Frederic Rissb8b43d52015-03-04 22:07:44 +00002105/// \brief Assign an abbreviation numer to \p Abbrev.
2106///
2107/// Our DIEs get freed after every DebugMapObject has been processed,
2108/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2109/// the instances hold by the DIEs. When we encounter an abbreviation
2110/// that we don't know, we create a permanent copy of it.
2111void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2112 // Check the set for priors.
2113 FoldingSetNodeID ID;
2114 Abbrev.Profile(ID);
2115 void *InsertToken;
2116 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2117
2118 // If it's newly added.
2119 if (InSet) {
2120 // Assign existing abbreviation number.
2121 Abbrev.setNumber(InSet->getNumber());
2122 } else {
2123 // Add to abbreviation list.
2124 Abbreviations.push_back(
2125 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2126 for (const auto &Attr : Abbrev.getData())
2127 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2128 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2129 // Assign the unique abbreviation number.
2130 Abbrev.setNumber(Abbreviations.size());
2131 Abbreviations.back()->setNumber(Abbreviations.size());
2132 }
2133}
2134
2135/// \brief Clone a string attribute described by \p AttrSpec and add
2136/// it to \p Die.
2137/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00002138unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
2139 const DWARFFormValue &Val,
2140 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002141 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002142 const char *String = *Val.getAsCString(&U);
2143 unsigned Offset = StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002144 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002145 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002146 return 4;
2147}
2148
2149/// \brief Clone an attribute referencing another DIE and add
2150/// it to \p Die.
2151/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00002152unsigned DwarfLinker::cloneDieReferenceAttribute(
2153 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2154 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002155 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002156 const DWARFUnit &U = Unit.getOrigUnit();
2157 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002158 DIE *NewRefDie = nullptr;
2159 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002160 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002161
Frederic Riss1c650942015-07-21 22:41:43 +00002162 const DWARFDebugInfoEntryMinimal *RefDie =
2163 resolveDIEReference(Val, U, InputDIE, RefUnit);
2164
2165 // If the referenced DIE is not found, drop the attribute.
2166 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002167 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002168
2169 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2170 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002171
2172 // If we already have emitted an equivalent DeclContext, just point
2173 // at it.
2174 if (isODRAttribute(AttrSpec.Attr)) {
2175 Ctxt = RefInfo.Ctxt;
2176 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2177 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2178 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2179 dwarf::DW_FORM_ref_addr, Attr);
2180 return getRefAddrSize(U);
2181 }
2182 }
2183
Frederic Riss9833de62015-03-06 23:22:53 +00002184 if (!RefInfo.Clone) {
2185 assert(Ref > InputDIE.getOffset());
2186 // We haven't cloned this DIE yet. Just create an empty one and
2187 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002188 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002189 }
2190 NewRefDie = RefInfo.Clone;
2191
Frederic Riss1c650942015-07-21 22:41:43 +00002192 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2193 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002194 // We cannot currently rely on a DIEEntry to emit ref_addr
2195 // references, because the implementation calls back to DwarfDebug
2196 // to find the unit offset. (We don't have a DwarfDebug)
2197 // FIXME: we should be able to design DIEEntry reliance on
2198 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002199 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002200 if (Ref < InputDIE.getOffset()) {
2201 // We must have already cloned that DIE.
2202 uint32_t NewRefOffset =
2203 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002204 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002205 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2206 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002207 } else {
2208 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002209 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002210 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002211 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002212 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2213 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002214 }
Frederic Riss1c650942015-07-21 22:41:43 +00002215 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002216 }
2217
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002218 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2219 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002220 return AttrSize;
2221}
2222
2223/// \brief Clone an attribute of block form (locations, constants) and add
2224/// it to \p Die.
2225/// \returns the size of the new attribute.
2226unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
2227 const DWARFFormValue &Val,
2228 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002229 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002230 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002231 DIELoc *Loc = nullptr;
2232 DIEBlock *Block = nullptr;
2233 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002234 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002235 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002236 DIELocs.push_back(Loc);
2237 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002238 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002239 DIEBlocks.push_back(Block);
2240 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002241 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2242 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002243
2244 if (Loc)
2245 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2246 dwarf::Form(AttrSpec.Form), Loc);
2247 else
2248 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2249 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002250 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2251 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002252 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2253 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002254 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2255 // the DIE class, this if could be replaced by
2256 // Attr->setSize(Bytes.size()).
2257 if (Streamer) {
2258 if (Loc)
2259 Loc->ComputeSize(&Streamer->getAsmPrinter());
2260 else
2261 Block->ComputeSize(&Streamer->getAsmPrinter());
2262 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002263 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002264 return AttrSize;
2265}
2266
Frederic Riss31da3242015-03-11 18:45:52 +00002267/// \brief Clone an address attribute and add it to \p Die.
2268/// \returns the size of the new attribute.
2269unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
2270 const DWARFFormValue &Val,
2271 const CompileUnit &Unit,
2272 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002273 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002274 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2275 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2276 Die.getTag() == dwarf::DW_TAG_lexical_block)
2277 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002278 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2279 Addr = Unit.getLowPc();
2280 if (Addr == UINT64_MAX)
2281 return 0;
2282 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002283 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002284 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002285 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2286 if (uint64_t HighPc = Unit.getHighPc())
2287 Addr = HighPc;
2288 else
2289 return 0;
2290 } else
2291 // If we have a high_pc recorded for the input DIE, use
2292 // it. Otherwise (when no relocations where applied) just use the
2293 // one we just decoded.
2294 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002295 }
2296
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002297 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002298 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002299 return Unit.getOrigUnit().getAddressByteSize();
2300}
2301
Frederic Rissb8b43d52015-03-04 22:07:44 +00002302/// \brief Clone a scalar attribute and add it to \p Die.
2303/// \returns the size of the new attribute.
2304unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002305 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002306 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002307 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002308 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002309 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2310 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2311 if (Unit.getLowPc() == -1ULL)
2312 return 0;
2313 // Dwarf >= 4 high_pc is an size, not an address.
2314 Value = Unit.getHighPc() - Unit.getLowPc();
2315 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002316 Value = *Val.getAsSectionOffset();
2317 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2318 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002319 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2320 Value = *OptionalValue;
2321 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002322 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2323 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002324 return 0;
2325 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002326 PatchLocation Patch =
2327 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2328 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002329 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002330 Unit.noteRangeAttribute(Die, Patch);
Frederic Rissdfb97902015-03-14 15:49:07 +00002331 // A more generic way to check for location attributes would be
2332 // nice, but it's very unlikely that any other attribute needs a
2333 // location list.
2334 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2335 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002336 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002337 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2338 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002339
Frederic Rissb8b43d52015-03-04 22:07:44 +00002340 return AttrSize;
2341}
2342
2343/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2344/// value \p Val, and add it to \p Die.
2345/// \returns the size of the cloned attribute.
2346unsigned DwarfLinker::cloneAttribute(DIE &Die,
2347 const DWARFDebugInfoEntryMinimal &InputDIE,
2348 CompileUnit &Unit,
2349 const DWARFFormValue &Val,
2350 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00002351 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002352 const DWARFUnit &U = Unit.getOrigUnit();
2353
2354 switch (AttrSpec.Form) {
2355 case dwarf::DW_FORM_strp:
2356 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002357 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002358 case dwarf::DW_FORM_ref_addr:
2359 case dwarf::DW_FORM_ref1:
2360 case dwarf::DW_FORM_ref2:
2361 case dwarf::DW_FORM_ref4:
2362 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002363 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002364 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002365 case dwarf::DW_FORM_block:
2366 case dwarf::DW_FORM_block1:
2367 case dwarf::DW_FORM_block2:
2368 case dwarf::DW_FORM_block4:
2369 case dwarf::DW_FORM_exprloc:
2370 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2371 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002372 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002373 case dwarf::DW_FORM_data1:
2374 case dwarf::DW_FORM_data2:
2375 case dwarf::DW_FORM_data4:
2376 case dwarf::DW_FORM_data8:
2377 case dwarf::DW_FORM_udata:
2378 case dwarf::DW_FORM_sdata:
2379 case dwarf::DW_FORM_sec_offset:
2380 case dwarf::DW_FORM_flag:
2381 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002382 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2383 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002384 default:
2385 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2386 &InputDIE);
2387 }
2388
2389 return 0;
2390}
2391
Frederic Riss23e20e92015-03-07 01:25:09 +00002392/// \brief Apply the valid relocations found by findValidRelocs() to
2393/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2394/// in the debug_info section.
2395///
2396/// Like for findValidRelocs(), this function must be called with
2397/// monotonic \p BaseOffset values.
2398///
2399/// \returns wether any reloc has been applied.
2400bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2401 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002402 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002403 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2404 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002405 if (NextValidReloc >= ValidRelocs.size())
2406 return false;
2407
2408 // Skip relocs that haven't been applied.
2409 while (NextValidReloc < ValidRelocs.size() &&
2410 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2411 ++NextValidReloc;
2412
2413 bool Applied = false;
2414 uint64_t EndOffset = BaseOffset + Data.size();
2415 while (NextValidReloc < ValidRelocs.size() &&
2416 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2417 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2418 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2419 assert(ValidReloc.Offset - BaseOffset < Data.size());
2420 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2421 char Buf[8];
2422 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2423 Value += ValidReloc.Addend;
2424 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2425 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2426 Buf[i] = uint8_t(Value >> (Index * 8));
2427 }
2428 assert(ValidReloc.Size <= sizeof(Buf));
2429 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2430 Applied = true;
2431 }
2432
2433 return Applied;
2434}
2435
Frederic Rissbce93ff2015-03-16 02:05:10 +00002436static bool isTypeTag(uint16_t Tag) {
2437 switch (Tag) {
2438 case dwarf::DW_TAG_array_type:
2439 case dwarf::DW_TAG_class_type:
2440 case dwarf::DW_TAG_enumeration_type:
2441 case dwarf::DW_TAG_pointer_type:
2442 case dwarf::DW_TAG_reference_type:
2443 case dwarf::DW_TAG_string_type:
2444 case dwarf::DW_TAG_structure_type:
2445 case dwarf::DW_TAG_subroutine_type:
2446 case dwarf::DW_TAG_typedef:
2447 case dwarf::DW_TAG_union_type:
2448 case dwarf::DW_TAG_ptr_to_member_type:
2449 case dwarf::DW_TAG_set_type:
2450 case dwarf::DW_TAG_subrange_type:
2451 case dwarf::DW_TAG_base_type:
2452 case dwarf::DW_TAG_const_type:
2453 case dwarf::DW_TAG_constant:
2454 case dwarf::DW_TAG_file_type:
2455 case dwarf::DW_TAG_namelist:
2456 case dwarf::DW_TAG_packed_type:
2457 case dwarf::DW_TAG_volatile_type:
2458 case dwarf::DW_TAG_restrict_type:
2459 case dwarf::DW_TAG_interface_type:
2460 case dwarf::DW_TAG_unspecified_type:
2461 case dwarf::DW_TAG_shared_type:
2462 return true;
2463 default:
2464 break;
2465 }
2466 return false;
2467}
2468
Frederic Rissb8b43d52015-03-04 22:07:44 +00002469/// \brief Recursively clone \p InputDIE's subtrees that have been
2470/// selected to appear in the linked output.
2471///
2472/// \param OutOffset is the Offset where the newly created DIE will
2473/// lie in the linked compile unit.
2474///
2475/// \returns the cloned DIE object or null if nothing was selected.
2476DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002477 CompileUnit &Unit, int64_t PCOffset,
2478 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002479 DWARFUnit &U = Unit.getOrigUnit();
2480 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002481 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002482
2483 // Should the DIE appear in the output?
2484 if (!Unit.getInfo(Idx).Keep)
2485 return nullptr;
2486
2487 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002488 // The DIE might have been already created by a forward reference
2489 // (see cloneDieReferenceAttribute()).
2490 DIE *Die = Info.Clone;
2491 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002492 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002493 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002494 Die->setOffset(OutOffset);
Frederic Riss1c650942015-07-21 22:41:43 +00002495 if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2496 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2497 !Info.Ctxt->getCanonicalDIEOffset()) {
2498 // We are about to emit a DIE that is the root of its own valid
2499 // DeclContext tree. Make the current offset the canonical offset
2500 // for this context.
2501 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2502 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002503
2504 // Extract and clone every attribute.
2505 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002506 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002507 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002508
2509 // We could copy the data only if we need to aply a relocation to
2510 // it. After testing, it seems there is no performance downside to
2511 // doing the copy unconditionally, and it makes the code simpler.
2512 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2513 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2514 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002515 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2516 // If we applied relocations, we store the value of high_pc that was
2517 // potentially stored in the input DIE. If high_pc is an address
2518 // (Dwarf version == 2), then it might have been relocated to a
2519 // totally unrelated value (because the end address in the object
2520 // file might be start address of another function which got moved
2521 // independantly by the linker). The computation of the actual
2522 // high_pc value is done in cloneAddressAttribute().
2523 AttrInfo.OrigHighPc =
2524 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2525 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002526
2527 // Reset the Offset to 0 as we will be working on the local copy of
2528 // the data.
2529 Offset = 0;
2530
Frederic Rissb8b43d52015-03-04 22:07:44 +00002531 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2532 Offset += getULEB128Size(Abbrev->getCode());
2533
Frederic Riss31da3242015-03-11 18:45:52 +00002534 // We are entering a subprogram. Get and propagate the PCOffset.
2535 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2536 PCOffset = Info.AddrAdjust;
2537 AttrInfo.PCOffset = PCOffset;
2538
Frederic Rissb8b43d52015-03-04 22:07:44 +00002539 for (const auto &AttrSpec : Abbrev->attributes()) {
2540 DWARFFormValue Val(AttrSpec.Form);
2541 uint32_t AttrSize = Offset;
2542 Val.extractValue(Data, &Offset, &U);
2543 AttrSize = Offset - AttrSize;
2544
Frederic Riss31da3242015-03-11 18:45:52 +00002545 OutOffset +=
2546 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002547 }
2548
Frederic Rissbce93ff2015-03-16 02:05:10 +00002549 // Look for accelerator entries.
2550 uint16_t Tag = InputDIE.getTag();
2551 // FIXME: This is slightly wrong. An inline_subroutine without a
2552 // low_pc, but with AT_ranges might be interesting to get into the
2553 // accelerator tables too. For now stick with dsymutil's behavior.
2554 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2555 Tag != dwarf::DW_TAG_compile_unit &&
2556 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2557 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2558 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2559 AttrInfo.MangledNameOffset,
2560 Tag == dwarf::DW_TAG_inlined_subroutine);
2561 if (AttrInfo.Name)
2562 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2563 Tag == dwarf::DW_TAG_inlined_subroutine);
2564 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2565 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2566 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2567 }
2568
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002569 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002570 // If a scope DIE is kept, we must have kept at least one child. If
2571 // it's not the case, we'll just be emitting one wasteful end of
2572 // children marker, but things won't break.
2573 if (InputDIE.hasChildren())
2574 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2575 // Assign a permanent abbrev number
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002576 AssignAbbrev(NewAbbrev);
2577 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002578
2579 // Add the size of the abbreviation number to the output offset.
2580 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2581
2582 if (!Abbrev->hasChildren()) {
2583 // Update our size.
2584 Die->setSize(OutOffset - Die->getOffset());
2585 return Die;
2586 }
2587
2588 // Recursively clone children.
2589 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2590 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002591 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002592 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002593 OutOffset = Clone->getOffset() + Clone->getSize();
2594 }
2595 }
2596
2597 // Account for the end of children marker.
2598 OutOffset += sizeof(int8_t);
2599 // Update our size.
2600 Die->setSize(OutOffset - Die->getOffset());
2601 return Die;
2602}
2603
Frederic Riss25440872015-03-13 23:30:31 +00002604/// \brief Patch the input object file relevant debug_ranges entries
2605/// and emit them in the output file. Update the relevant attributes
2606/// to point at the new entries.
2607void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2608 DWARFContext &OrigDwarf) const {
2609 DWARFDebugRangeList RangeList;
2610 const auto &FunctionRanges = Unit.getFunctionRanges();
2611 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2612 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2613 OrigDwarf.isLittleEndian(), AddressSize);
2614 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2615 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002616 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002617 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2618 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2619 // Ranges addresses are based on the unit's low_pc. Compute the
2620 // offset we need to apply to adapt to the the new unit's low_pc.
2621 int64_t UnitPcOffset = 0;
2622 if (OrigLowPc != -1ULL)
2623 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2624
2625 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002626 uint32_t Offset = RangeAttribute.get();
2627 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002628 RangeList.extract(RangeExtractor, &Offset);
2629 const auto &Entries = RangeList.getEntries();
2630 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2631
2632 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2633 First.StartAddress >= CurrRange.stop()) {
2634 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2635 if (CurrRange == InvalidRange ||
2636 CurrRange.start() > First.StartAddress + OrigLowPc) {
2637 reportWarning("no mapping for range.");
2638 continue;
2639 }
2640 }
2641
2642 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2643 AddressSize);
2644 }
2645}
2646
Frederic Riss563b1b02015-03-14 03:46:51 +00002647/// \brief Generate the debug_aranges entries for \p Unit and if the
2648/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2649/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002650/// FIXME: this could actually be done right in patchRangesForUnit,
2651/// but for the sake of initial bit-for-bit compatibility with legacy
2652/// dsymutil, we have to do it in a delayed pass.
2653void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002654 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002655 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002656 Attr->set(Streamer->getRangesSectionSize());
2657 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002658}
2659
Frederic Riss63786b02015-03-15 20:45:43 +00002660/// \brief Insert the new line info sequence \p Seq into the current
2661/// set of already linked line info \p Rows.
2662static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2663 std::vector<DWARFDebugLine::Row> &Rows) {
2664 if (Seq.empty())
2665 return;
2666
2667 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2668 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2669 Seq.clear();
2670 return;
2671 }
2672
2673 auto InsertPoint = std::lower_bound(
2674 Rows.begin(), Rows.end(), Seq.front(),
2675 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2676 return LHS.Address < RHS.Address;
2677 });
2678
2679 // FIXME: this only removes the unneeded end_sequence if the
2680 // sequences have been inserted in order. using a global sort like
2681 // described in patchLineTableForUnit() and delaying the end_sequene
2682 // elimination to emitLineTableForUnit() we can get rid of all of them.
2683 if (InsertPoint != Rows.end() &&
2684 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2685 *InsertPoint = Seq.front();
2686 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2687 } else {
2688 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2689 }
2690
2691 Seq.clear();
2692}
2693
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002694static void patchStmtList(DIE &Die, DIEInteger Offset) {
2695 for (auto &V : Die.values())
2696 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002697 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002698 return;
2699 }
2700
2701 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2702}
2703
Frederic Riss63786b02015-03-15 20:45:43 +00002704/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2705/// recreate a relocated version of these for the address ranges that
2706/// are present in the binary.
2707void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2708 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002709 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002710 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2711 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2712 if (StmtList == -1ULL)
2713 return;
2714
2715 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002716 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2717 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002718
2719 // Parse the original line info for the unit.
2720 DWARFDebugLine::LineTable LineTable;
2721 uint32_t StmtOffset = StmtList;
2722 StringRef LineData = OrigDwarf.getLineSection().Data;
2723 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2724 Unit.getOrigUnit().getAddressByteSize());
2725 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2726 &StmtOffset);
2727
2728 // This vector is the output line table.
2729 std::vector<DWARFDebugLine::Row> NewRows;
2730 NewRows.reserve(LineTable.Rows.size());
2731
2732 // Current sequence of rows being extracted, before being inserted
2733 // in NewRows.
2734 std::vector<DWARFDebugLine::Row> Seq;
2735 const auto &FunctionRanges = Unit.getFunctionRanges();
2736 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2737
2738 // FIXME: This logic is meant to generate exactly the same output as
2739 // Darwin's classic dsynutil. There is a nicer way to implement this
2740 // by simply putting all the relocated line info in NewRows and simply
2741 // sorting NewRows before passing it to emitLineTableForUnit. This
2742 // should be correct as sequences for a function should stay
2743 // together in the sorted output. There are a few corner cases that
2744 // look suspicious though, and that required to implement the logic
2745 // this way. Revisit that once initial validation is finished.
2746
2747 // Iterate over the object file line info and extract the sequences
2748 // that correspond to linked functions.
2749 for (auto &Row : LineTable.Rows) {
2750 // Check wether we stepped out of the range. The range is
2751 // half-open, but consider accept the end address of the range if
2752 // it is marked as end_sequence in the input (because in that
2753 // case, the relocation offset is accurate and that entry won't
2754 // serve as the start of another function).
2755 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2756 Row.Address > CurrRange.stop() ||
2757 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2758 // We just stepped out of a known range. Insert a end_sequence
2759 // corresponding to the end of the range.
2760 uint64_t StopAddress = CurrRange != InvalidRange
2761 ? CurrRange.stop() + CurrRange.value()
2762 : -1ULL;
2763 CurrRange = FunctionRanges.find(Row.Address);
2764 bool CurrRangeValid =
2765 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2766 if (!CurrRangeValid) {
2767 CurrRange = InvalidRange;
2768 if (StopAddress != -1ULL) {
2769 // Try harder by looking in the DebugMapObject function
2770 // ranges map. There are corner cases where this finds a
2771 // valid entry. It's unclear if this is right or wrong, but
2772 // for now do as dsymutil.
2773 // FIXME: Understand exactly what cases this addresses and
2774 // potentially remove it along with the Ranges map.
2775 auto Range = Ranges.lower_bound(Row.Address);
2776 if (Range != Ranges.begin() && Range != Ranges.end())
2777 --Range;
2778
2779 if (Range != Ranges.end() && Range->first <= Row.Address &&
2780 Range->second.first >= Row.Address) {
2781 StopAddress = Row.Address + Range->second.second;
2782 }
2783 }
2784 }
2785 if (StopAddress != -1ULL && !Seq.empty()) {
2786 // Insert end sequence row with the computed end address, but
2787 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00002788 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00002789 NextLine.Address = StopAddress;
2790 NextLine.EndSequence = 1;
2791 NextLine.PrologueEnd = 0;
2792 NextLine.BasicBlock = 0;
2793 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00002794 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00002795 insertLineSequence(Seq, NewRows);
2796 }
2797
2798 if (!CurrRangeValid)
2799 continue;
2800 }
2801
2802 // Ignore empty sequences.
2803 if (Row.EndSequence && Seq.empty())
2804 continue;
2805
2806 // Relocate row address and add it to the current sequence.
2807 Row.Address += CurrRange.value();
2808 Seq.emplace_back(Row);
2809
2810 if (Row.EndSequence)
2811 insertLineSequence(Seq, NewRows);
2812 }
2813
2814 // Finished extracting, now emit the line tables.
2815 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2816 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2817 // prologue over and that works because we act as both producer and
2818 // consumer. It would be nicer to have a real configurable line
2819 // table emitter.
2820 if (LineTable.Prologue.Version != 2 ||
2821 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00002822 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00002823 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00002824 else {
2825 MCDwarfLineTableParams Params;
2826 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
2827 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
2828 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
2829 Streamer->emitLineTableForUnit(Params,
2830 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00002831 LineTable.Prologue.MinInstLength, NewRows,
2832 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00002833 }
Frederic Riss63786b02015-03-15 20:45:43 +00002834}
2835
Frederic Rissbce93ff2015-03-16 02:05:10 +00002836void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2837 Streamer->emitPubNamesForUnit(Unit);
2838 Streamer->emitPubTypesForUnit(Unit);
2839}
2840
Frederic Riss5a642072015-06-05 23:06:11 +00002841/// \brief Read the frame info stored in the object, and emit the
2842/// patched frame descriptions for the linked binary.
2843///
2844/// This is actually pretty easy as the data of the CIEs and FDEs can
2845/// be considered as black boxes and moved as is. The only thing to do
2846/// is to patch the addresses in the headers.
2847void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2848 DWARFContext &OrigDwarf,
2849 unsigned AddrSize) {
2850 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2851 if (FrameData.empty())
2852 return;
2853
2854 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2855 uint32_t InputOffset = 0;
2856
2857 // Store the data of the CIEs defined in this object, keyed by their
2858 // offsets.
2859 DenseMap<uint32_t, StringRef> LocalCIES;
2860
2861 while (Data.isValidOffset(InputOffset)) {
2862 uint32_t EntryOffset = InputOffset;
2863 uint32_t InitialLength = Data.getU32(&InputOffset);
2864 if (InitialLength == 0xFFFFFFFF)
2865 return reportWarning("Dwarf64 bits no supported");
2866
2867 uint32_t CIEId = Data.getU32(&InputOffset);
2868 if (CIEId == 0xFFFFFFFF) {
2869 // This is a CIE, store it.
2870 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2871 LocalCIES[EntryOffset] = CIEData;
2872 // The -4 is to account for the CIEId we just read.
2873 InputOffset += InitialLength - 4;
2874 continue;
2875 }
2876
2877 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2878
2879 // Some compilers seem to emit frame info that doesn't start at
2880 // the function entry point, thus we can't just lookup the address
2881 // in the debug map. Use the linker's range map to see if the FDE
2882 // describes something that we can relocate.
2883 auto Range = Ranges.upper_bound(Loc);
2884 if (Range != Ranges.begin())
2885 --Range;
2886 if (Range == Ranges.end() || Range->first > Loc ||
2887 Range->second.first <= Loc) {
2888 // The +4 is to account for the size of the InitialLength field itself.
2889 InputOffset = EntryOffset + InitialLength + 4;
2890 continue;
2891 }
2892
2893 // This is an FDE, and we have a mapping.
2894 // Have we already emitted a corresponding CIE?
2895 StringRef CIEData = LocalCIES[CIEId];
2896 if (CIEData.empty())
2897 return reportWarning("Inconsistent debug_frame content. Dropping.");
2898
2899 // Look if we already emitted a CIE that corresponds to the
2900 // referenced one (the CIE data is the key of that lookup).
2901 auto IteratorInserted = EmittedCIEs.insert(
2902 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2903 // If there is no CIE yet for this ID, emit it.
2904 if (IteratorInserted.second ||
2905 // FIXME: dsymutil-classic only caches the last used CIE for
2906 // reuse. Mimic that behavior for now. Just removing that
2907 // second half of the condition and the LastCIEOffset variable
2908 // makes the code DTRT.
2909 LastCIEOffset != IteratorInserted.first->getValue()) {
2910 LastCIEOffset = Streamer->getFrameSectionSize();
2911 IteratorInserted.first->getValue() = LastCIEOffset;
2912 Streamer->emitCIE(CIEData);
2913 }
2914
2915 // Emit the FDE with updated address and CIE pointer.
2916 // (4 + AddrSize) is the size of the CIEId + initial_location
2917 // fields that will get reconstructed by emitFDE().
2918 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
2919 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
2920 Loc + Range->second.second,
2921 FrameData.substr(InputOffset, FDERemainingBytes));
2922 InputOffset += FDERemainingBytes;
2923 }
2924}
2925
Frederic Risseb85c8f2015-07-24 06:41:11 +00002926ErrorOr<const object::ObjectFile &>
2927DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
2928 const DebugMap &Map) {
2929 auto ErrOrObjs =
2930 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
2931 if (std::error_code EC = ErrOrObjs.getError())
2932 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
2933 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
2934 if (std::error_code EC = ErrOrObj.getError())
2935 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
2936 return ErrOrObj;
2937}
2938
Frederic Rissd3455182015-01-28 18:27:01 +00002939bool DwarfLinker::link(const DebugMap &Map) {
2940
Frederic Rissc99ea202015-02-28 00:29:11 +00002941 if (!createStreamer(Map.getTriple(), OutputFilename))
2942 return false;
2943
Frederic Rissb8b43d52015-03-04 22:07:44 +00002944 // Size of the DIEs (and headers) generated for the linked output.
2945 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002946 // A unique ID that identifies each compile unit.
2947 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002948 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002949 CurrentDebugObject = Obj.get();
2950
Frederic Rissb9818322015-02-28 00:29:07 +00002951 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002952 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00002953 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
2954 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00002955 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00002956
Frederic Riss1036e642015-02-13 23:18:22 +00002957 // Look for relocations that correspond to debug map entries.
2958 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002959 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002960 outs() << "No valid relocations found. Skipping.\n";
2961 continue;
2962 }
2963
Frederic Riss563cba62015-01-28 22:15:14 +00002964 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002965 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002966 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002967
Frederic Riss563cba62015-01-28 22:15:14 +00002968 // In a first phase, just read in the debug info and store the DIE
2969 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002970 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002971 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002972 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002973 outs() << "Input compilation unit:";
2974 CUDie->dump(outs(), CU.get(), 0);
2975 }
Frederic Riss1c650942015-07-21 22:41:43 +00002976 Units.emplace_back(*CU, UnitID++, !Options.NoODR);
2977 gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
2978 StringPool, ODRContexts);
Frederic Rissd3455182015-01-28 18:27:01 +00002979 }
Frederic Riss563cba62015-01-28 22:15:14 +00002980
Frederic Riss84c09a52015-02-13 23:18:34 +00002981 // Then mark all the DIEs that need to be present in the linked
2982 // output and collect some information about them. Note that this
2983 // loop can not be merged with the previous one becaue cross-cu
2984 // references require the ParentIdx to be setup for every CU in
2985 // the object file before calling this.
2986 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002987 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00002988 CurrentUnit, 0);
2989
Frederic Riss23e20e92015-03-07 01:25:09 +00002990 // The calls to applyValidRelocs inside cloneDIE will walk the
2991 // reloc array again (in the same way findValidRelocsInDebugInfo()
2992 // did). We need to reset the NextValidReloc index to the beginning.
2993 NextValidReloc = 0;
2994
Frederic Rissb8b43d52015-03-04 22:07:44 +00002995 // Construct the output DIE tree by cloning the DIEs we chose to
2996 // keep above. If there are no valid relocs, then there's nothing
2997 // to clone/emit.
2998 if (!ValidRelocs.empty())
2999 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003000 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00003001 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00003002 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
3003 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00003004 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00003005 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00003006 if (Options.NoOutput)
3007 continue;
3008 // FIXME: for compatibility with the classic dsymutil, we emit
3009 // an empty line table for the unit, even if the unit doesn't
3010 // actually exist in the DIE tree.
3011 patchLineTableForUnit(CurrentUnit, DwarfContext);
3012 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00003013 continue;
3014 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00003015 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00003016 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00003017 }
3018
3019 // Emit all the compile unit's debug information.
3020 if (!ValidRelocs.empty() && !Options.NoOutput)
3021 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00003022 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00003023 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00003024 Streamer->emitCompileUnitHeader(CurrentUnit);
3025 if (!CurrentUnit.getOutputUnitDIE())
3026 continue;
3027 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3028 }
3029
Frederic Riss5a642072015-06-05 23:06:11 +00003030 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
3031 patchFrameInfoForObject(*Obj, DwarfContext,
3032 Units[0].getOrigUnit().getAddressByteSize());
3033
Frederic Riss563cba62015-01-28 22:15:14 +00003034 // Clean-up before starting working on the next object.
3035 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003036 }
3037
Frederic Rissb8b43d52015-03-04 22:07:44 +00003038 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003039 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003040 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003041 Streamer->emitStrings(StringPool);
3042 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003043
Frederic Rissc99ea202015-02-28 00:29:11 +00003044 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00003045}
3046}
Frederic Rissd3455182015-01-28 18:27:01 +00003047
Frederic Riss30711fb2015-08-26 05:09:52 +00003048/// \brief Get the offset of string \p S in the string table. This
3049/// can insert a new element or return the offset of a preexisitng
3050/// one.
3051uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3052 if (S.empty() && !Strings.empty())
3053 return 0;
3054
3055 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3056 MapTy::iterator It;
3057 bool Inserted;
3058
3059 // A non-empty string can't be at offset 0, so if we have an entry
3060 // with a 0 offset, it must be a previously interned string.
3061 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3062 if (Inserted || It->getValue().first == 0) {
3063 // Set offset and chain at the end of the entries list.
3064 It->getValue().first = CurrentEndOffset;
3065 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3066 Last->getValue().second = &*It;
3067 Last = &*It;
3068 }
3069 return It->getValue().first;
3070}
3071
3072/// \brief Put \p S into the StringMap so that it gets permanent
3073/// storage, but do not actually link it in the chain of elements
3074/// that go into the output section. A latter call to
3075/// getStringOffset() with the same string will chain it though.
3076StringRef NonRelocatableStringpool::internString(StringRef S) {
3077 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3078 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3079 return InsertResult.first->getKey();
3080}
3081
Frederic Riss65e145c2015-08-26 05:09:55 +00003082void warn(const Twine &Warning, const Twine &Context) {
3083 errs() << Twine("while processing ") + Context + ":\n";
3084 errs() << Twine("warning: ") + Warning + "\n";
3085}
3086
3087bool error(const Twine &Error, const Twine &Context) {
3088 errs() << Twine("while processing ") + Context + ":\n";
3089 errs() << Twine("error: ") + Error + "\n";
3090 return false;
3091}
3092
Frederic Rissb9818322015-02-28 00:29:07 +00003093bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3094 const LinkOptions &Options) {
3095 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003096 return Linker.link(DM);
3097}
3098}
Frederic Riss231f7142014-12-12 17:31:24 +00003099}