blob: fb7ffceec8fc371ffda29c5e4d31923d8f3c4c00 [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 Riss24faade2015-09-02 16:49:13 +000013#include "MachOUtils.h"
Frederic Riss30711fb2015-08-26 05:09:52 +000014#include "NonRelocatableStringpool.h"
Frederic Riss1af75f72015-03-12 18:45:10 +000015#include "llvm/ADT/IntervalMap.h"
Adrian Prantle5162db2015-09-22 22:20:50 +000016#include "llvm/ADT/StringSet.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000017#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000018#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000019#include "llvm/CodeGen/DIE.h"
Frederic Riss1c650942015-07-21 22:41:43 +000020#include "llvm/Config/config.h"
Zachary Turner82af9432015-01-30 18:07:45 +000021#include "llvm/DebugInfo/DWARF/DWARFContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000023#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000024#include "llvm/MC/MCAsmBackend.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000028#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000029#include "llvm/MC/MCInstrInfo.h"
30#include "llvm/MC/MCObjectFileInfo.h"
31#include "llvm/MC/MCRegisterInfo.h"
32#include "llvm/MC/MCStreamer.h"
Pete Cooper81902a32015-05-15 22:19:42 +000033#include "llvm/MC/MCSubtargetInfo.h"
Frederic Riss1036e642015-02-13 23:18:22 +000034#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000035#include "llvm/Support/Dwarf.h"
36#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000037#include "llvm/Support/TargetRegistry.h"
38#include "llvm/Target/TargetMachine.h"
39#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000040#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000041#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000042
43namespace llvm {
44namespace dsymutil {
45
Frederic Rissd3455182015-01-28 18:27:01 +000046namespace {
47
Frederic Riss1af75f72015-03-12 18:45:10 +000048template <typename KeyT, typename ValT>
49using HalfOpenIntervalMap =
50 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
51 IntervalMapHalfOpenInfo<KeyT>>;
52
Frederic Riss25440872015-03-13 23:30:31 +000053typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
54
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000055// FIXME: Delete this structure.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000056struct PatchLocation {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000057 DIE::value_iterator I;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000058
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000059 PatchLocation() = default;
60 PatchLocation(DIE::value_iterator I) : I(I) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000061
62 void set(uint64_t New) const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000063 assert(I);
64 const auto &Old = *I;
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000065 assert(Old.getType() == DIEValue::isInteger);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000066 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000067 }
68
69 uint64_t get() const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000070 assert(I);
71 return I->getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000072 }
73};
74
Frederic Riss1c650942015-07-21 22:41:43 +000075class CompileUnit;
76struct DeclMapInfo;
Frederic Riss1c650942015-07-21 22:41:43 +000077
78/// A DeclContext is a named program scope that is used for ODR
79/// uniquing of types.
80/// The set of DeclContext for the ODR-subject parts of a Dwarf link
81/// is expanded (and uniqued) with each new object file processed. We
82/// need to determine the context of each DIE in an linked object file
83/// to see if the corresponding type has already been emitted.
84///
85/// The contexts are conceptually organised as a tree (eg. a function
86/// scope is contained in a namespace scope that contains other
87/// scopes), but storing/accessing them in an actual tree is too
88/// inefficient: we need to be able to very quickly query a context
89/// for a given child context by name. Storing a StringMap in each
90/// DeclContext would be too space inefficient.
91/// The solution here is to give each DeclContext a link to its parent
92/// (this allows to walk up the tree), but to query the existance of a
93/// specific DeclContext using a separate DenseMap keyed on the hash
94/// of the fully qualified name of the context.
95class DeclContext {
96 unsigned QualifiedNameHash;
97 uint32_t Line;
98 uint32_t ByteSize;
99 uint16_t Tag;
100 StringRef Name;
101 StringRef File;
102 const DeclContext &Parent;
103 const DWARFDebugInfoEntryMinimal *LastSeenDIE;
104 uint32_t LastSeenCompileUnitID;
105 uint32_t CanonicalDIEOffset;
106
107 friend DeclMapInfo;
108
109public:
110 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
111
112 DeclContext()
113 : QualifiedNameHash(0), Line(0), ByteSize(0),
114 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
115 LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
116
117 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
118 StringRef Name, StringRef File, const DeclContext &Parent,
119 const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
120 unsigned CUId = 0)
121 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
122 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
123 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
124
125 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
126
127 bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
128
129 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
130 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
131
132 uint16_t getTag() const { return Tag; }
133 StringRef getName() const { return Name; }
134};
135
136/// Info type for the DenseMap storing the DeclContext pointers.
137struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
138 using DenseMapInfo<DeclContext *>::getEmptyKey;
139 using DenseMapInfo<DeclContext *>::getTombstoneKey;
140
141 static unsigned getHashValue(const DeclContext *Ctxt) {
142 return Ctxt->QualifiedNameHash;
143 }
144
145 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
146 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
147 return RHS == LHS;
148 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
149 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
150 LHS->Name.data() == RHS->Name.data() &&
151 LHS->File.data() == RHS->File.data() &&
152 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
153 }
154};
155
156/// This class gives a tree-like API to the DenseMap that stores the
157/// DeclContext objects. It also holds the BumpPtrAllocator where
158/// these objects will be allocated.
159class DeclContextTree {
160 BumpPtrAllocator Allocator;
161 DeclContext Root;
162 DeclContext::Map Contexts;
163
164public:
165 /// Get the child of \a Context described by \a DIE in \a Unit. The
166 /// required strings will be interned in \a StringPool.
167 /// \returns The child DeclContext along with one bit that is set if
168 /// this context is invalid.
169 /// FIXME: the invalid bit along the return value is to emulate some
170 /// dsymutil-classic functionality. See the fucntion definition for
171 /// a more thorough discussion of its use.
172 PointerIntPair<DeclContext *, 1>
173 getChildDeclContext(DeclContext &Context,
174 const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
175 NonRelocatableStringpool &StringPool);
176
177 DeclContext &getRoot() { return Root; }
178};
179
Frederic Riss563cba62015-01-28 22:15:14 +0000180/// \brief Stores all information relating to a compile unit, be it in
181/// its original instance in the object file to its brand new cloned
182/// and linked DIE tree.
183class CompileUnit {
184public:
185 /// \brief Information gathered about a DIE in the object file.
186 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +0000187 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss1c650942015-07-21 22:41:43 +0000188 DeclContext *Ctxt; ///< ODR Declaration context.
Frederic Riss9833de62015-03-06 23:22:53 +0000189 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +0000190 uint32_t ParentIdx; ///< The index of this DIE's parent.
191 bool Keep; ///< Is the DIE part of the linked output?
192 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +0000193 };
194
Frederic Riss1c650942015-07-21 22:41:43 +0000195 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR)
Frederic Riss3cced052015-03-14 03:46:40 +0000196 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000197 Ranges(RangeAlloc) {
Frederic Riss563cba62015-01-28 22:15:14 +0000198 Info.resize(OrigUnit.getNumDIEs());
Frederic Riss1c650942015-07-21 22:41:43 +0000199
200 const auto *CUDie = OrigUnit.getUnitDIE(false);
201 unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
202 &OrigUnit, dwarf::DW_AT_language, 0);
203 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
204 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
205 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
206 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
207 Lang == dwarf::DW_LANG_ObjC_plus_plus);
Frederic Riss563cba62015-01-28 22:15:14 +0000208 }
209
Frederic Riss2838f9e2015-03-05 05:29:05 +0000210 CompileUnit(CompileUnit &&RHS)
211 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
212 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000213 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
214 // The CompileUnit container has been 'reserve()'d with the right
215 // size. We cannot move the IntervalMap anyway.
216 llvm_unreachable("CompileUnits should not be moved.");
217 }
David Blaikiea8adc132015-03-04 22:20:52 +0000218
Frederic Rissc3349d42015-02-13 23:18:27 +0000219 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000220
Frederic Riss3cced052015-03-14 03:46:40 +0000221 unsigned getUniqueID() const { return ID; }
222
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +0000223 DIE *getOutputUnitDIE() const { return CUDie; }
224 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000225
Frederic Riss1c650942015-07-21 22:41:43 +0000226 bool hasODR() const { return HasODR; }
227
Frederic Riss563cba62015-01-28 22:15:14 +0000228 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
229 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
230
Frederic Rissb8b43d52015-03-04 22:07:44 +0000231 uint64_t getStartOffset() const { return StartOffset; }
232 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000233 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000234
Frederic Riss5a62dc32015-03-13 18:35:54 +0000235 uint64_t getLowPc() const { return LowPc; }
236 uint64_t getHighPc() const { return HighPc; }
237
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000238 Optional<PatchLocation> getUnitRangesAttribute() const {
239 return UnitRangeAttribute;
240 }
Frederic Riss25440872015-03-13 23:30:31 +0000241 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000242 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000243 return RangeAttributes;
244 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000245
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000246 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000247 getLocationAttributes() const {
248 return LocationAttributes;
249 }
250
Adrian Prantle5162db2015-09-22 22:20:50 +0000251 void setHasInterestingContent() { HasInterestingContent = true; }
252 bool hasInterestingContent() { return HasInterestingContent; }
253
254 /// Mark every DIE in this unit as kept. This function also
255 /// marks variables as InDebugMap so that they appear in the
256 /// reconstructed accelerator tables.
257 void markEverythingAsKept();
258
Frederic Riss9d441b62015-03-06 23:22:50 +0000259 /// \brief Compute the end offset for this unit. Must be
260 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000261 /// \returns the next unit offset (which is also the current
262 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000263 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000264
Frederic Riss6afcfce2015-03-13 18:35:57 +0000265 /// \brief Keep track of a forward reference to DIE \p Die in \p
266 /// RefUnit by \p Attr. The attribute should be fixed up later to
Frederic Riss1c650942015-07-21 22:41:43 +0000267 /// point to the absolute offset of \p Die in the debug_info section
268 /// or to the canonical offset of \p Ctxt if it is non-null.
Frederic Riss6afcfce2015-03-13 18:35:57 +0000269 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000270 DeclContext *Ctxt, PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000271
272 /// \brief Apply all fixups recored by noteForwardReference().
273 void fixupForwardReferences();
274
Frederic Riss1af75f72015-03-12 18:45:10 +0000275 /// \brief Add a function range [\p LowPC, \p HighPC) that is
276 /// relocatad by applying offset \p PCOffset.
277 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
278
Frederic Riss5c9c7062015-03-13 23:55:29 +0000279 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000280 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000281 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000282
Frederic Rissdfb97902015-03-14 15:49:07 +0000283 /// \brief Keep track of a location attribute pointing to a location
284 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000285 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000286
Frederic Rissbce93ff2015-03-16 02:05:10 +0000287 /// \brief Add a name accelerator entry for \p Die with \p Name
288 /// which is stored in the string table at \p Offset.
289 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
290 bool SkipPubnamesSection = false);
291
292 /// \brief Add a type accelerator entry for \p Die with \p Name
293 /// which is stored in the string table at \p Offset.
294 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
295
296 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000297 StringRef Name; ///< Name of the entry.
298 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000299 uint32_t NameOffset; ///< Offset of Name in the string pool.
300 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
301
302 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
303 bool SkipPubSection = false)
304 : Name(Name), Die(Die), NameOffset(NameOffset),
305 SkipPubSection(SkipPubSection) {}
306 };
307
308 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
309 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
310
Frederic Riss1c650942015-07-21 22:41:43 +0000311 /// Get the full path for file \a FileNum in the line table
312 const char *getResolvedPath(unsigned FileNum) {
313 if (FileNum >= ResolvedPaths.size())
314 return nullptr;
315 return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
316 : nullptr;
317 }
318
319 /// Set the fully resolved path for the line-table's file \a FileNum
320 /// to \a Path.
321 void setResolvedPath(unsigned FileNum, const std::string &Path) {
322 if (ResolvedPaths.size() <= FileNum)
323 ResolvedPaths.resize(FileNum + 1);
324 ResolvedPaths[FileNum] = Path;
325 }
326
Frederic Riss563cba62015-01-28 22:15:14 +0000327private:
328 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000329 unsigned ID;
Frederic Riss1c650942015-07-21 22:41:43 +0000330 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
331 DIE *CUDie; ///< Root of the linked DIE tree.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000332
333 uint64_t StartOffset;
334 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000335
Frederic Riss5a62dc32015-03-13 18:35:54 +0000336 uint64_t LowPc;
337 uint64_t HighPc;
338
Frederic Riss9833de62015-03-06 23:22:53 +0000339 /// \brief A list of attributes to fixup with the absolute offset of
340 /// a DIE in the debug_info section.
341 ///
342 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000343 /// cloning because for cross-cu forward refences the target DIE's
344 /// offset isn't known you emit the reference attribute.
Frederic Riss1c650942015-07-21 22:41:43 +0000345 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
346 PatchLocation>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000347
Frederic Riss25440872015-03-13 23:30:31 +0000348 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000349 /// \brief The ranges in that interval map are the PC ranges for
350 /// functions in this unit, associated with the PC offset to apply
351 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000352 FunctionIntervals Ranges;
353
354 /// \brief DW_AT_ranges attributes to patch after we have gathered
355 /// all the unit's function addresses.
356 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000357 std::vector<PatchLocation> RangeAttributes;
358 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000359 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000360
361 /// \brief Location attributes that need to be transfered from th
362 /// original debug_loc section to the liked one. They are stored
363 /// along with the PC offset that is to be applied to their
364 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000365 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000366
367 /// \brief Accelerator entries for the unit, both for the pub*
368 /// sections and the apple* ones.
369 /// @{
370 std::vector<AccelInfo> Pubnames;
371 std::vector<AccelInfo> Pubtypes;
372 /// @}
Frederic Riss1c650942015-07-21 22:41:43 +0000373
374 /// Cached resolved paths from the line table.
375 std::vector<std::string> ResolvedPaths;
376
377 /// Is this unit subject to the ODR rule?
378 bool HasODR;
Adrian Prantle5162db2015-09-22 22:20:50 +0000379 /// Did a DIE actually contain a valid reloc?
380 bool HasInterestingContent;
Frederic Riss563cba62015-01-28 22:15:14 +0000381};
382
Adrian Prantle5162db2015-09-22 22:20:50 +0000383void CompileUnit::markEverythingAsKept() {
384 for (auto &I : Info)
385 I.Keep = true;
386}
387
Frederic Riss9d441b62015-03-06 23:22:50 +0000388uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000389 NextUnitOffset = StartOffset + 11 /* Header size */;
390 // The root DIE might be null, meaning that the Unit had nothing to
391 // contribute to the linked output. In that case, we will emit the
392 // unit header without any actual DIE.
393 if (CUDie)
394 NextUnitOffset += CUDie->getSize();
395 return NextUnitOffset;
396}
397
Frederic Riss6afcfce2015-03-13 18:35:57 +0000398/// \brief Keep track of a forward cross-cu reference from this unit
399/// to \p Die that lives in \p RefUnit.
400void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000401 DeclContext *Ctxt, PatchLocation Attr) {
402 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000403}
404
405/// \brief Apply all fixups recorded by noteForwardReference().
406void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000407 for (const auto &Ref : ForwardDIEReferences) {
408 DIE *RefDie;
409 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000410 PatchLocation Attr;
Frederic Riss1c650942015-07-21 22:41:43 +0000411 DeclContext *Ctxt;
412 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
413 if (Ctxt && Ctxt->getCanonicalDIEOffset())
414 Attr.set(Ctxt->getCanonicalDIEOffset());
415 else
416 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000417 }
Frederic Riss9833de62015-03-06 23:22:53 +0000418}
419
Frederic Riss5a62dc32015-03-13 18:35:54 +0000420void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
421 int64_t PcOffset) {
422 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
423 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
424 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000425}
426
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000427void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000428 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
429 RangeAttributes.push_back(Attr);
430 else
431 UnitRangeAttribute = Attr;
432}
433
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000434void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000435 LocationAttributes.emplace_back(Attr, PcOffset);
436}
437
Frederic Rissbce93ff2015-03-16 02:05:10 +0000438/// \brief Add a name accelerator entry for \p Die with \p Name
439/// which is stored in the string table at \p Offset.
440void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
441 uint32_t Offset, bool SkipPubSection) {
442 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
443}
444
445/// \brief Add a type accelerator entry for \p Die with \p Name
446/// which is stored in the string table at \p Offset.
447void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
448 uint32_t Offset) {
449 Pubtypes.emplace_back(Name, Die, Offset, false);
450}
451
Frederic Rissc99ea202015-02-28 00:29:11 +0000452/// \brief The Dwarf streaming logic
453///
454/// All interactions with the MC layer that is used to build the debug
455/// information binary representation are handled in this class.
456class DwarfStreamer {
457 /// \defgroup MCObjects MC layer objects constructed by the streamer
458 /// @{
459 std::unique_ptr<MCRegisterInfo> MRI;
460 std::unique_ptr<MCAsmInfo> MAI;
461 std::unique_ptr<MCObjectFileInfo> MOFI;
462 std::unique_ptr<MCContext> MC;
463 MCAsmBackend *MAB; // Owned by MCStreamer
464 std::unique_ptr<MCInstrInfo> MII;
465 std::unique_ptr<MCSubtargetInfo> MSTI;
466 MCCodeEmitter *MCE; // Owned by MCStreamer
467 MCStreamer *MS; // Owned by AsmPrinter
468 std::unique_ptr<TargetMachine> TM;
469 std::unique_ptr<AsmPrinter> Asm;
470 /// @}
471
472 /// \brief the file we stream the linked Dwarf to.
473 std::unique_ptr<raw_fd_ostream> OutFile;
474
Frederic Riss25440872015-03-13 23:30:31 +0000475 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000476 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000477 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000478 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000479
Frederic Rissbce93ff2015-03-16 02:05:10 +0000480 /// \brief Emit the pubnames or pubtypes section contribution for \p
481 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000482 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000483 const CompileUnit &Unit,
484 const std::vector<CompileUnit::AccelInfo> &Names);
485
Frederic Rissc99ea202015-02-28 00:29:11 +0000486public:
487 /// \brief Actually create the streamer and the ouptut file.
488 ///
489 /// This could be done directly in the constructor, but it feels
490 /// more natural to handle errors through return value.
491 bool init(Triple TheTriple, StringRef OutputFilename);
492
Frederic Rissb8b43d52015-03-04 22:07:44 +0000493 /// \brief Dump the file to the disk.
Frederic Riss24faade2015-09-02 16:49:13 +0000494 bool finish(const DebugMap &);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000495
496 AsmPrinter &getAsmPrinter() const { return *Asm; }
497
498 /// \brief Set the current output section to debug_info and change
499 /// the MC Dwarf version to \p DwarfVersion.
500 void switchToDebugInfoSection(unsigned DwarfVersion);
501
502 /// \brief Emit the compilation unit header for \p Unit in the
503 /// debug_info section.
504 ///
505 /// As a side effect, this also switches the current Dwarf version
506 /// of the MC layer to the one of U.getOrigUnit().
507 void emitCompileUnitHeader(CompileUnit &Unit);
508
509 /// \brief Recursively emit the DIE tree rooted at \p Die.
510 void emitDIE(DIE &Die);
511
512 /// \brief Emit the abbreviation table \p Abbrevs to the
513 /// debug_abbrev section.
514 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000515
516 /// \brief Emit the string table described by \p Pool.
517 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000518
519 /// \brief Emit debug_ranges for \p FuncRange by translating the
520 /// original \p Entries.
521 void emitRangesEntries(
522 int64_t UnitPcOffset, uint64_t OrigLowPc,
523 FunctionIntervals::const_iterator FuncRange,
524 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
525 unsigned AddressSize);
526
Frederic Riss563b1b02015-03-14 03:46:51 +0000527 /// \brief Emit debug_aranges entries for \p Unit and if \p
528 /// DoRangesSection is true, also emit the debug_ranges entries for
529 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
530 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000531
532 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000533
534 /// \brief Emit the debug_loc contribution for \p Unit by copying
535 /// the entries from \p Dwarf and offseting them. Update the
536 /// location attributes to point to the new entries.
537 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000538
539 /// \brief Emit the line table described in \p Rows into the
540 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000541 void emitLineTableForUnit(MCDwarfLineTableParams Params,
542 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000543 std::vector<DWARFDebugLine::Row> &Rows,
544 unsigned AdddressSize);
545
546 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000547
548 /// \brief Emit the .debug_pubnames contribution for \p Unit.
549 void emitPubNamesForUnit(const CompileUnit &Unit);
550
551 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
552 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000553
554 /// \brief Emit a CIE.
555 void emitCIE(StringRef CIEBytes);
556
557 /// \brief Emit an FDE with data \p Bytes.
558 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
559 StringRef Bytes);
560
561 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000562};
563
564bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
565 std::string ErrorStr;
566 std::string TripleName;
567 StringRef Context = "dwarf streamer init";
568
569 // Get the target.
570 const Target *TheTarget =
571 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
572 if (!TheTarget)
573 return error(ErrorStr, Context);
574 TripleName = TheTriple.getTriple();
575
576 // Create all the MC Objects.
577 MRI.reset(TheTarget->createMCRegInfo(TripleName));
578 if (!MRI)
579 return error(Twine("no register info for target ") + TripleName, Context);
580
581 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
582 if (!MAI)
583 return error("no asm info for target " + TripleName, Context);
584
585 MOFI.reset(new MCObjectFileInfo);
586 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000587 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
Frederic Rissc99ea202015-02-28 00:29:11 +0000588 *MC);
589
590 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
591 if (!MAB)
592 return error("no asm backend for target " + TripleName, Context);
593
594 MII.reset(TheTarget->createMCInstrInfo());
595 if (!MII)
596 return error("no instr info info for target " + TripleName, Context);
597
598 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
599 if (!MSTI)
600 return error("no subtarget info for target " + TripleName, Context);
601
Eric Christopher0169e422015-03-10 22:03:14 +0000602 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000603 if (!MCE)
604 return error("no code emitter for target " + TripleName, Context);
605
606 // Create the output file.
607 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000608 OutFile =
609 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000610 if (EC)
611 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
612
Daniel Sanders50f17232015-09-15 16:17:27 +0000613 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
614 *MSTI, false,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000615 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000616 if (!MS)
617 return error("no object streamer for target " + TripleName, Context);
618
619 // Finally create the AsmPrinter we'll use to emit the DIEs.
620 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
621 if (!TM)
622 return error("no target machine for target " + TripleName, Context);
623
624 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
625 if (!Asm)
626 return error("no asm printer for target " + TripleName, Context);
627
Frederic Riss25440872015-03-13 23:30:31 +0000628 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000629 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000630 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000631 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000632
Frederic Rissc99ea202015-02-28 00:29:11 +0000633 return true;
634}
635
Frederic Riss24faade2015-09-02 16:49:13 +0000636bool DwarfStreamer::finish(const DebugMap &DM) {
637 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
638 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
639
Frederic Rissc99ea202015-02-28 00:29:11 +0000640 MS->Finish();
641 return true;
642}
643
Frederic Rissb8b43d52015-03-04 22:07:44 +0000644/// \brief Set the current output section to debug_info and change
645/// the MC Dwarf version to \p DwarfVersion.
646void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
647 MS->SwitchSection(MOFI->getDwarfInfoSection());
648 MC->setDwarfVersion(DwarfVersion);
649}
650
651/// \brief Emit the compilation unit header for \p Unit in the
652/// debug_info section.
653///
654/// A Dwarf scetion header is encoded as:
655/// uint32_t Unit length (omiting this field)
656/// uint16_t Version
657/// uint32_t Abbreviation table offset
658/// uint8_t Address size
659///
660/// Leading to a total of 11 bytes.
661void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
662 unsigned Version = Unit.getOrigUnit().getVersion();
663 switchToDebugInfoSection(Version);
664
665 // Emit size of content not including length itself. The size has
666 // already been computed in CompileUnit::computeOffsets(). Substract
667 // 4 to that size to account for the length field.
668 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
669 Asm->EmitInt16(Version);
670 // We share one abbreviations table across all units so it's always at the
671 // start of the section.
672 Asm->EmitInt32(0);
673 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
674}
675
676/// \brief Emit the \p Abbrevs array as the shared abbreviation table
677/// for the linked Dwarf file.
678void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
679 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
680 Asm->emitDwarfAbbrevs(Abbrevs);
681}
682
683/// \brief Recursively emit the DIE tree rooted at \p Die.
684void DwarfStreamer::emitDIE(DIE &Die) {
685 MS->SwitchSection(MOFI->getDwarfInfoSection());
686 Asm->emitDwarfDIE(Die);
687}
688
Frederic Rissef648462015-03-06 17:56:30 +0000689/// \brief Emit the debug_str section stored in \p Pool.
690void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000691 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000692 for (auto *Entry = Pool.getFirstEntry(); Entry;
693 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000694 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000695 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
696}
697
Frederic Riss25440872015-03-13 23:30:31 +0000698/// \brief Emit the debug_range section contents for \p FuncRange by
699/// translating the original \p Entries. The debug_range section
700/// format is totally trivial, consisting just of pairs of address
701/// sized addresses describing the ranges.
702void DwarfStreamer::emitRangesEntries(
703 int64_t UnitPcOffset, uint64_t OrigLowPc,
704 FunctionIntervals::const_iterator FuncRange,
705 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
706 unsigned AddressSize) {
707 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
708
709 // Offset each range by the right amount.
Frederic Riss94546202015-08-31 05:09:32 +0000710 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
Frederic Riss25440872015-03-13 23:30:31 +0000711 for (const auto &Range : Entries) {
712 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
713 warn("unsupported base address selection operation",
714 "emitting debug_ranges");
715 break;
716 }
717 // Do not emit empty ranges.
718 if (Range.StartAddress == Range.EndAddress)
719 continue;
720
721 // All range entries should lie in the function range.
722 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
723 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
724 warn("inconsistent range data.", "emitting debug_ranges");
725 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
726 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
727 RangesSectionSize += 2 * AddressSize;
728 }
729
730 // Add the terminator entry.
731 MS->EmitIntValue(0, AddressSize);
732 MS->EmitIntValue(0, AddressSize);
733 RangesSectionSize += 2 * AddressSize;
734}
735
Frederic Riss563b1b02015-03-14 03:46:51 +0000736/// \brief Emit the debug_aranges contribution of a unit and
737/// if \p DoDebugRanges is true the debug_range contents for a
738/// compile_unit level DW_AT_ranges attribute (Which are basically the
739/// same thing with a different base address).
740/// Just aggregate all the ranges gathered inside that unit.
741void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
742 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000743 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
744 // Gather the ranges in a vector, so that we can simplify them. The
745 // IntervalMap will have coalesced the non-linked ranges, but here
746 // we want to coalesce the linked addresses.
747 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
748 const auto &FunctionRanges = Unit.getFunctionRanges();
749 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
750 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000751 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
752 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000753
754 // The object addresses where sorted, but again, the linked
755 // addresses might end up in a different order.
756 std::sort(Ranges.begin(), Ranges.end());
757
Frederic Riss563b1b02015-03-14 03:46:51 +0000758 if (!Ranges.empty()) {
759 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
760
Rafael Espindola9ab09232015-03-17 20:07:06 +0000761 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
762 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000763
764 unsigned HeaderSize =
765 sizeof(int32_t) + // Size of contents (w/o this field
766 sizeof(int16_t) + // DWARF ARange version number
767 sizeof(int32_t) + // Offset of CU in the .debug_info section
768 sizeof(int8_t) + // Pointer Size (in bytes)
769 sizeof(int8_t); // Segment Size (in bytes)
770
771 unsigned TupleSize = AddressSize * 2;
772 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
773
774 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000775 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000776 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
777 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
778 Asm->EmitInt8(AddressSize); // Address size
779 Asm->EmitInt8(0); // Segment size
780
Lang Hames9ff69c82015-04-24 19:11:51 +0000781 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000782
783 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
784 ++Range) {
785 uint64_t RangeStart = Range->first;
786 MS->EmitIntValue(RangeStart, AddressSize);
787 while ((Range + 1) != End && Range->second == (Range + 1)->first)
788 ++Range;
789 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
790 }
791
792 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000793 Asm->OutStreamer->EmitIntValue(0, AddressSize);
794 Asm->OutStreamer->EmitIntValue(0, AddressSize);
795 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000796 }
797
798 if (!DoDebugRanges)
799 return;
800
801 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
802 // Offset each range by the right amount.
803 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000804 // Emit coalesced ranges.
805 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000806 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000807 while (Range + 1 != End && Range->second == (Range + 1)->first)
808 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000809 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000810 RangesSectionSize += 2 * AddressSize;
811 }
812
813 // Add the terminator entry.
814 MS->EmitIntValue(0, AddressSize);
815 MS->EmitIntValue(0, AddressSize);
816 RangesSectionSize += 2 * AddressSize;
817}
818
Frederic Rissdfb97902015-03-14 15:49:07 +0000819/// \brief Emit location lists for \p Unit and update attribtues to
820/// point to the new entries.
821void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
822 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000823 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000824
825 if (Attributes.empty())
826 return;
827
828 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
829
830 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
831 const DWARFSection &InputSec = Dwarf.getLocSection();
832 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
833 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000834 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000835 int64_t UnitPcOffset = 0;
836 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
837 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
838 if (OrigLowPc != -1ULL)
839 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
840
841 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000842 uint32_t Offset = Attr.first.get();
843 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000844 // This is the quantity to add to the old location address to get
845 // the correct address for the new one.
846 int64_t LocPcOffset = Attr.second + UnitPcOffset;
847 while (Data.isValidOffset(Offset)) {
848 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
849 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
850 LocSectionSize += 2 * AddressSize;
851 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000852 Asm->OutStreamer->EmitIntValue(0, AddressSize);
853 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000854 break;
855 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000856 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
857 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000858 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000859 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000860 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000861 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000862 StringRef(InputSec.Data.substr(Offset, Length)));
863 Offset += Length;
864 LocSectionSize += Length + 2;
865 }
866 }
867}
868
Frederic Rissa5e14532015-08-07 15:14:13 +0000869void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
870 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000871 unsigned MinInstLength,
872 std::vector<DWARFDebugLine::Row> &Rows,
873 unsigned PointerSize) {
874 // Switch to the section where the table will be emitted into.
875 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000876 MCSymbol *LineStartSym = MC->createTempSymbol();
877 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000878
879 // The first 4 bytes is the total length of the information for this
880 // compilation unit (not including these 4 bytes for the length).
881 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000882 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000883 // Copy Prologue.
884 MS->EmitBytes(PrologueBytes);
885 LineSectionSize += PrologueBytes.size() + 4;
886
Frederic Rissc3820d02015-03-15 22:20:28 +0000887 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000888 raw_svector_ostream EncodingOS(EncodingBuffer);
889
890 if (Rows.empty()) {
891 // We only have the dummy entry, dsymutil emits an entry with a 0
892 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000893 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000894 MS->EmitBytes(EncodingOS.str());
895 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000896 MS->EmitLabel(LineEndSym);
897 return;
898 }
899
900 // Line table state machine fields
901 unsigned FileNum = 1;
902 unsigned LastLine = 1;
903 unsigned Column = 0;
904 unsigned IsStatement = 1;
905 unsigned Isa = 0;
906 uint64_t Address = -1ULL;
907
908 unsigned RowsSinceLastSequence = 0;
909
910 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
911 auto &Row = Rows[Idx];
912
913 int64_t AddressDelta;
914 if (Address == -1ULL) {
915 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
916 MS->EmitULEB128IntValue(PointerSize + 1);
917 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
918 MS->EmitIntValue(Row.Address, PointerSize);
919 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
920 AddressDelta = 0;
921 } else {
922 AddressDelta = (Row.Address - Address) / MinInstLength;
923 }
924
925 // FIXME: code copied and transfromed from
926 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
927 // this code, but the current compatibility requirement with
928 // classic dsymutil makes it hard. Revisit that once this
929 // requirement is dropped.
930
931 if (FileNum != Row.File) {
932 FileNum = Row.File;
933 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
934 MS->EmitULEB128IntValue(FileNum);
935 LineSectionSize += 1 + getULEB128Size(FileNum);
936 }
937 if (Column != Row.Column) {
938 Column = Row.Column;
939 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
940 MS->EmitULEB128IntValue(Column);
941 LineSectionSize += 1 + getULEB128Size(Column);
942 }
943
944 // FIXME: We should handle the discriminator here, but dsymutil
945 // doesn' consider it, thus ignore it for now.
946
947 if (Isa != Row.Isa) {
948 Isa = Row.Isa;
949 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
950 MS->EmitULEB128IntValue(Isa);
951 LineSectionSize += 1 + getULEB128Size(Isa);
952 }
953 if (IsStatement != Row.IsStmt) {
954 IsStatement = Row.IsStmt;
955 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
956 LineSectionSize += 1;
957 }
958 if (Row.BasicBlock) {
959 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
960 LineSectionSize += 1;
961 }
962
963 if (Row.PrologueEnd) {
964 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
965 LineSectionSize += 1;
966 }
967
968 if (Row.EpilogueBegin) {
969 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
970 LineSectionSize += 1;
971 }
972
973 int64_t LineDelta = int64_t(Row.Line) - LastLine;
974 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000975 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000976 MS->EmitBytes(EncodingOS.str());
977 LineSectionSize += EncodingBuffer.size();
978 EncodingBuffer.resize(0);
979 Address = Row.Address;
980 LastLine = Row.Line;
981 RowsSinceLastSequence++;
982 } else {
983 if (LineDelta) {
984 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
985 MS->EmitSLEB128IntValue(LineDelta);
986 LineSectionSize += 1 + getSLEB128Size(LineDelta);
987 }
988 if (AddressDelta) {
989 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
990 MS->EmitULEB128IntValue(AddressDelta);
991 LineSectionSize += 1 + getULEB128Size(AddressDelta);
992 }
Frederic Rissa5e14532015-08-07 15:14:13 +0000993 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000994 MS->EmitBytes(EncodingOS.str());
995 LineSectionSize += EncodingBuffer.size();
996 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +0000997 Address = -1ULL;
998 LastLine = FileNum = IsStatement = 1;
999 RowsSinceLastSequence = Column = Isa = 0;
1000 }
1001 }
1002
1003 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +00001004 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001005 MS->EmitBytes(EncodingOS.str());
1006 LineSectionSize += EncodingBuffer.size();
1007 EncodingBuffer.resize(0);
1008 }
1009
1010 MS->EmitLabel(LineEndSym);
1011}
1012
Frederic Rissbce93ff2015-03-16 02:05:10 +00001013/// \brief Emit the pubnames or pubtypes section contribution for \p
1014/// Unit into \p Sec. The data is provided in \p Names.
1015void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001016 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001017 const std::vector<CompileUnit::AccelInfo> &Names) {
1018 if (Names.empty())
1019 return;
1020
1021 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001022 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001023 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1024 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001025
1026 bool HeaderEmitted = false;
1027 // Emit the pubnames for this compilation unit.
1028 for (const auto &Name : Names) {
1029 if (Name.SkipPubSection)
1030 continue;
1031
1032 if (!HeaderEmitted) {
1033 // Emit the header.
1034 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001035 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001036 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001037 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001038 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1039 HeaderEmitted = true;
1040 }
1041 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001042 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001043 StringRef(Name.Name.data(), Name.Name.size() + 1));
1044 }
1045
1046 if (!HeaderEmitted)
1047 return;
1048 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001049 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001050}
1051
1052/// \brief Emit .debug_pubnames for \p Unit.
1053void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1054 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1055 "names", Unit, Unit.getPubnames());
1056}
1057
1058/// \brief Emit .debug_pubtypes for \p Unit.
1059void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1060 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1061 "types", Unit, Unit.getPubtypes());
1062}
1063
Frederic Riss5a642072015-06-05 23:06:11 +00001064/// \brief Emit a CIE into the debug_frame section.
1065void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1066 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1067
1068 MS->EmitBytes(CIEBytes);
1069 FrameSectionSize += CIEBytes.size();
1070}
1071
1072/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1073/// contains the FDE data without the length, CIE offset and address
1074/// which will be replaced with the paramter values.
1075void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1076 uint32_t Address, StringRef FDEBytes) {
1077 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1078
1079 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1080 MS->EmitIntValue(CIEOffset, 4);
1081 MS->EmitIntValue(Address, AddrSize);
1082 MS->EmitBytes(FDEBytes);
1083 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1084}
1085
Frederic Rissd3455182015-01-28 18:27:01 +00001086/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001087///
1088/// The link of the dwarf information from the object files will be
1089/// driven by the selection of 'root DIEs', which are DIEs that
1090/// describe variables or functions that are present in the linked
1091/// binary (and thus have entries in the debug map). All the debug
1092/// information that will be linked (the DIEs, but also the line
1093/// tables, ranges, ...) is derived from that set of root DIEs.
1094///
1095/// The root DIEs are identified because they contain relocations that
1096/// correspond to a debug map entry at specific places (the low_pc for
1097/// a function, the location for a variable). These relocations are
1098/// called ValidRelocs in the DwarfLinker and are gathered as a very
1099/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001100class DwarfLinker {
1101public:
Frederic Rissb9818322015-02-28 00:29:07 +00001102 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1103 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001104 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001105
Frederic Rissb8b43d52015-03-04 22:07:44 +00001106 ~DwarfLinker() {
1107 for (auto *Abbrev : Abbreviations)
1108 delete Abbrev;
1109 }
1110
Frederic Rissd3455182015-01-28 18:27:01 +00001111 /// \brief Link the contents of the DebugMap.
1112 bool link(const DebugMap &);
1113
Adrian Prantlc3021ee2015-09-22 18:50:51 +00001114 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1115 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1116
Frederic Rissd3455182015-01-28 18:27:01 +00001117private:
Frederic Riss563cba62015-01-28 22:15:14 +00001118 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001119 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001120
1121 /// \brief Called at the end of a debug object link.
1122 void endDebugObject();
1123
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001124 /// Keeps track of relocations.
1125 class RelocationManager {
1126 struct ValidReloc {
1127 uint32_t Offset;
1128 uint32_t Size;
1129 uint64_t Addend;
1130 const DebugMapObject::DebugMapEntry *Mapping;
Frederic Riss1036e642015-02-13 23:18:22 +00001131
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001132 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1133 const DebugMapObject::DebugMapEntry *Mapping)
1134 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
Frederic Riss1036e642015-02-13 23:18:22 +00001135
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001136 bool operator<(const ValidReloc &RHS) const {
1137 return Offset < RHS.Offset;
1138 }
1139 };
1140
1141 DwarfLinker &Linker;
1142
1143 /// \brief The valid relocations for the current DebugMapObject.
1144 /// This vector is sorted by relocation offset.
1145 std::vector<ValidReloc> ValidRelocs;
1146
1147 /// \brief Index into ValidRelocs of the next relocation to
1148 /// consider. As we walk the DIEs in acsending file offset and as
1149 /// ValidRelocs is sorted by file offset, keeping this index
1150 /// uptodate is all we have to do to have a cheap lookup during the
1151 /// root DIE selection and during DIE cloning.
1152 unsigned NextValidReloc;
1153
1154 public:
1155 RelocationManager(DwarfLinker &Linker)
1156 : Linker(Linker), NextValidReloc(0) {}
1157
1158 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1159 /// \brief Reset the NextValidReloc counter.
1160 void resetValidRelocs() { NextValidReloc = 0; }
1161
1162 /// \defgroup FindValidRelocations Translate debug map into a list
1163 /// of relevant relocations
1164 ///
1165 /// @{
1166 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1167 const DebugMapObject &DMO);
1168
1169 bool findValidRelocs(const object::SectionRef &Section,
1170 const object::ObjectFile &Obj,
1171 const DebugMapObject &DMO);
1172
1173 void findValidRelocsMachO(const object::SectionRef &Section,
1174 const object::MachOObjectFile &Obj,
1175 const DebugMapObject &DMO);
1176 /// @}
1177
1178 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1179 CompileUnit::DIEInfo &Info);
1180
1181 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1182 bool isLittleEndian);
Frederic Riss1036e642015-02-13 23:18:22 +00001183 };
1184
Frederic Riss84c09a52015-02-13 23:18:34 +00001185 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1186 ///
1187 /// @{
1188 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1189 /// keep. Store that information in \p CU's DIEInfo.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001190 void lookForDIEsToKeep(RelocationManager &RelocMgr,
1191 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001192 const DebugMapObject &DMO, CompileUnit &CU,
1193 unsigned Flags);
1194
Adrian Prantle5162db2015-09-22 22:20:50 +00001195 /// If this compile unit is really a skeleton CU that points to a
1196 /// clang module, register it in ClangModules and return true.
1197 ///
1198 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1199 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1200 /// hash.
1201 bool registerModuleReference(const DWARFDebugInfoEntryMinimal &CUDie,
1202 const DWARFUnit &Unit, DebugMap &ModuleMap,
1203 unsigned Indent = 0);
1204
1205 /// Recursively add the debug info in this clang module .pcm
1206 /// file (and all the modules imported by it in a bottom-up fashion)
1207 /// to Units.
1208 void loadClangModule(StringRef Filename, StringRef ModulePath,
1209 DebugMap &ModuleMap, unsigned Indent = 0);
1210
Frederic Riss84c09a52015-02-13 23:18:34 +00001211 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1212 enum TravesalFlags {
1213 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1214 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1215 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1216 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001217 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss29eedc72015-09-11 04:17:30 +00001218 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
Frederic Riss84c09a52015-02-13 23:18:34 +00001219 };
1220
1221 /// \brief Mark the passed DIE as well as all the ones it depends on
1222 /// as kept.
Adrian Prantl6ec47122015-09-22 15:31:14 +00001223 void keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001224 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001225 CompileUnit::DIEInfo &MyInfo,
1226 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001227 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001228
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001229 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1230 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001231 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1232 unsigned Flags);
1233
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001234 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1235 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001236 CompileUnit &Unit,
1237 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1238
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001239 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1240 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001241 CompileUnit &Unit,
1242 CompileUnit::DIEInfo &MyInfo,
1243 unsigned Flags);
1244
1245 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1246 CompileUnit::DIEInfo &Info);
1247 /// @}
1248
Frederic Rissb8b43d52015-03-04 22:07:44 +00001249 /// \defgroup Linking Methods used to link the debug information
1250 ///
1251 /// @{
Frederic Rissb8b43d52015-03-04 22:07:44 +00001252
Adrian Prantl3565af42015-09-14 16:46:10 +00001253 class DIECloner {
1254 DwarfLinker &Linker;
1255 RelocationManager &RelocMgr;
1256 /// Allocator used for all the DIEValue objects.
1257 BumpPtrAllocator &DIEAlloc;
1258 MutableArrayRef<CompileUnit> CompileUnits;
1259 LinkOptions Options;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001260
Adrian Prantl3565af42015-09-14 16:46:10 +00001261 public:
1262 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1263 BumpPtrAllocator &DIEAlloc,
1264 MutableArrayRef<CompileUnit> CompileUnits, LinkOptions &Options)
1265 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1266 CompileUnits(CompileUnits), Options(Options) {}
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001267
Adrian Prantl3565af42015-09-14 16:46:10 +00001268 /// Recursively clone \p InputDIE into an tree of DIE objects
1269 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1270 /// stripped out and addresses have been rewritten according to the
1271 /// debug map.
1272 ///
1273 /// \param OutOffset is the offset the cloned DIE in the output
1274 /// compile unit.
1275 /// \param PCOffset (while cloning a function scope) is the offset
1276 /// applied to the entry point of the function to get the linked address.
1277 ///
1278 /// \returns the root of the cloned tree or null if nothing was selected.
Adrian Prantl3abe18d2015-09-14 23:27:26 +00001279 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Adrian Prantl3565af42015-09-14 16:46:10 +00001280 int64_t PCOffset, uint32_t OutOffset, unsigned Flags);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001281
Adrian Prantl3565af42015-09-14 16:46:10 +00001282 /// Construct the output DIE tree by cloning the DIEs we
1283 /// chose to keep above. If there are no valid relocs, then there's
1284 /// nothing to clone/emit.
1285 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001286
Adrian Prantl3565af42015-09-14 16:46:10 +00001287 private:
1288 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
Frederic Rissbce93ff2015-03-16 02:05:10 +00001289
Adrian Prantl3565af42015-09-14 16:46:10 +00001290 /// Information gathered and exchanged between the various
1291 /// clone*Attributes helpers about the attributes of a particular DIE.
1292 struct AttributesInfo {
1293 const char *Name, *MangledName; ///< Names.
1294 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
Frederic Riss31da3242015-03-11 18:45:52 +00001295
Adrian Prantl3565af42015-09-14 16:46:10 +00001296 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1297 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1298 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
Frederic Rissbce93ff2015-03-16 02:05:10 +00001299
Adrian Prantl3565af42015-09-14 16:46:10 +00001300 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1301 bool IsDeclaration; ///< Is this DIE only a declaration?
1302
1303 AttributesInfo()
1304 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1305 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1306 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1307 };
1308
1309 /// Helper for cloneDIE.
1310 unsigned cloneAttribute(DIE &Die,
1311 const DWARFDebugInfoEntryMinimal &InputDIE,
1312 CompileUnit &U, const DWARFFormValue &Val,
1313 const AttributeSpec AttrSpec, unsigned AttrSize,
1314 AttributesInfo &AttrInfo);
1315
1316 /// Clone a string attribute described by \p AttrSpec and add
1317 /// it to \p Die.
1318 /// \returns the size of the new attribute.
1319 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1320 const DWARFFormValue &Val,
1321 const DWARFUnit &U);
1322
1323 /// Clone an attribute referencing another DIE and add
1324 /// it to \p Die.
1325 /// \returns the size of the new attribute.
1326 unsigned
1327 cloneDieReferenceAttribute(DIE &Die,
1328 const DWARFDebugInfoEntryMinimal &InputDIE,
1329 AttributeSpec AttrSpec, unsigned AttrSize,
1330 const DWARFFormValue &Val, CompileUnit &Unit);
1331
1332 /// Clone an attribute referencing another DIE and add
1333 /// it to \p Die.
1334 /// \returns the size of the new attribute.
1335 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1336 const DWARFFormValue &Val, unsigned AttrSize);
1337
1338 /// Clone an attribute referencing another DIE and add
1339 /// it to \p Die.
1340 /// \returns the size of the new attribute.
1341 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1342 const DWARFFormValue &Val,
1343 const CompileUnit &Unit,
1344 AttributesInfo &Info);
1345
1346 /// Clone a scalar attribute and add it to \p Die.
1347 /// \returns the size of the new attribute.
1348 unsigned cloneScalarAttribute(DIE &Die,
1349 const DWARFDebugInfoEntryMinimal &InputDIE,
1350 CompileUnit &U, AttributeSpec AttrSpec,
1351 const DWARFFormValue &Val, unsigned AttrSize,
1352 AttributesInfo &Info);
1353
1354 /// Get the potential name and mangled name for the entity
1355 /// described by \p Die and store them in \Info if they are not
1356 /// already there.
1357 /// \returns is a name was found.
1358 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1359 AttributesInfo &Info);
1360
1361 /// Create a copy of abbreviation Abbrev.
1362 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
Frederic Riss31da3242015-03-11 18:45:52 +00001363 };
1364
Frederic Rissb8b43d52015-03-04 22:07:44 +00001365 /// \brief Assign an abbreviation number to \p Abbrev
1366 void AssignAbbrev(DIEAbbrev &Abbrev);
1367
1368 /// \brief FoldingSet that uniques the abbreviations.
1369 FoldingSet<DIEAbbrev> AbbreviationsSet;
1370 /// \brief Storage for the unique Abbreviations.
1371 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1372 /// be changed to a vecot of unique_ptrs.
1373 std::vector<DIEAbbrev *> Abbreviations;
1374
Frederic Riss25440872015-03-13 23:30:31 +00001375 /// \brief Compute and emit debug_ranges section for \p Unit, and
1376 /// patch the attributes referencing it.
1377 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1378
1379 /// \brief Generate and emit the DW_AT_ranges attribute for a
1380 /// compile_unit if it had one.
1381 void generateUnitRanges(CompileUnit &Unit) const;
1382
Frederic Riss63786b02015-03-15 20:45:43 +00001383 /// \brief Extract the line tables fromt he original dwarf, extract
1384 /// the relevant parts according to the linked function ranges and
1385 /// emit the result in the debug_line section.
1386 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1387
Frederic Rissbce93ff2015-03-16 02:05:10 +00001388 /// \brief Emit the accelerator entries for \p Unit.
1389 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1390
Frederic Riss5a642072015-06-05 23:06:11 +00001391 /// \brief Patch the frame info for an object file and emit it.
1392 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1393 unsigned AddressSize);
1394
Frederic Rissb8b43d52015-03-04 22:07:44 +00001395 /// \brief DIELoc objects that need to be destructed (but not freed!).
1396 std::vector<DIELoc *> DIELocs;
1397 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1398 std::vector<DIEBlock *> DIEBlocks;
1399 /// \brief Allocator used for all the DIEValue objects.
1400 BumpPtrAllocator DIEAlloc;
1401 /// @}
1402
Frederic Riss1c650942015-07-21 22:41:43 +00001403 /// ODR Contexts for that link.
1404 DeclContextTree ODRContexts;
1405
Frederic Riss1b9da422015-02-13 23:18:29 +00001406 /// \defgroup Helpers Various helper methods.
1407 ///
1408 /// @{
Frederic Rissc99ea202015-02-28 00:29:11 +00001409 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001410
1411 /// \brief Attempt to load a debug object from disk.
1412 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1413 DebugMapObject &Obj,
1414 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001415 /// @}
1416
Frederic Rissd3455182015-01-28 18:27:01 +00001417 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001418 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001419 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001420 std::unique_ptr<DwarfStreamer> Streamer;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001421 uint64_t OutputDebugInfoSize;
Adrian Prantle5162db2015-09-22 22:20:50 +00001422 unsigned UnitID; ///< A unique ID that identifies each compile unit.
Frederic Riss563cba62015-01-28 22:15:14 +00001423
1424 /// The units of the current debug map object.
1425 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001426
1427 /// The debug map object curently under consideration.
1428 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001429
1430 /// \brief The Dwarf string pool
1431 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001432
1433 /// \brief This map is keyed by the entry PC of functions in that
1434 /// debug object and the associated value is a pair storing the
1435 /// corresponding end PC and the offset to apply to get the linked
1436 /// address.
1437 ///
1438 /// See startDebugObject() for a more complete description of its use.
1439 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001440
1441 /// \brief The CIEs that have been emitted in the output
1442 /// section. The actual CIE data serves a the key to this StringMap,
1443 /// this takes care of comparing the semantics of CIEs defined in
1444 /// different object files.
1445 StringMap<uint32_t> EmittedCIEs;
1446
1447 /// Offset of the last CIE that has been emitted in the output
1448 /// debug_frame section.
1449 uint32_t LastCIEOffset;
Adrian Prantle5162db2015-09-22 22:20:50 +00001450
1451 /// FIXME: We may need to use something more resilient than the PCM filename.
1452 StringSet<> ClangModules;
Frederic Rissd3455182015-01-28 18:27:01 +00001453};
1454
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001455/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1456/// CompileUnit object instead.
1457static CompileUnit *getUnitForOffset(MutableArrayRef<CompileUnit> Units,
1458 unsigned Offset) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001459 auto CU =
1460 std::upper_bound(Units.begin(), Units.end(), Offset,
1461 [](uint32_t LHS, const CompileUnit &RHS) {
1462 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1463 });
1464 return CU != Units.end() ? &*CU : nullptr;
1465}
1466
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001467/// Resolve the DIE attribute reference that has been
Frederic Riss1b9da422015-02-13 23:18:29 +00001468/// extracted in \p RefValue. The resulting DIE migh be in another
1469/// CompileUnit which is stored into \p ReferencedCU.
1470/// \returns null if resolving fails for any reason.
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001471static const DWARFDebugInfoEntryMinimal *resolveDIEReference(
1472 const DwarfLinker &Linker, MutableArrayRef<CompileUnit> Units,
Frederic Riss1c650942015-07-21 22:41:43 +00001473 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001474 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1475 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1476 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1477
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001478 if ((RefCU = getUnitForOffset(Units, RefOffset)))
Frederic Riss1b9da422015-02-13 23:18:29 +00001479 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1480 return RefDie;
1481
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001482 Linker.reportWarning("could not find referenced DIE", &Unit, &DIE);
Frederic Riss1b9da422015-02-13 23:18:29 +00001483 return nullptr;
1484}
1485
Frederic Riss1c650942015-07-21 22:41:43 +00001486/// \returns whether the passed \a Attr type might contain a DIE
1487/// reference suitable for ODR uniquing.
1488static bool isODRAttribute(uint16_t Attr) {
1489 switch (Attr) {
1490 default:
1491 return false;
1492 case dwarf::DW_AT_type:
1493 case dwarf::DW_AT_containing_type:
1494 case dwarf::DW_AT_specification:
1495 case dwarf::DW_AT_abstract_origin:
1496 case dwarf::DW_AT_import:
1497 return true;
1498 }
1499 llvm_unreachable("Improper attribute.");
1500}
1501
1502/// Set the last DIE/CU a context was seen in and, possibly invalidate
1503/// the context if it is ambiguous.
1504///
1505/// In the current implementation, we don't handle overloaded
1506/// functions well, because the argument types are not taken into
1507/// account when computing the DeclContext tree.
1508///
1509/// Some of this is mitigated byt using mangled names that do contain
1510/// the arguments types, but sometimes (eg. with function templates)
1511/// we don't have that. In that case, just do not unique anything that
1512/// refers to the contexts we are not able to distinguish.
1513///
1514/// If a context that is not a namespace appears twice in the same CU,
1515/// we know it is ambiguous. Make it invalid.
1516bool DeclContext::setLastSeenDIE(CompileUnit &U,
1517 const DWARFDebugInfoEntryMinimal *Die) {
1518 if (LastSeenCompileUnitID == U.getUniqueID()) {
1519 DWARFUnit &OrigUnit = U.getOrigUnit();
1520 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1521 U.getInfo(FirstIdx).Ctxt = nullptr;
1522 return false;
1523 }
1524
1525 LastSeenCompileUnitID = U.getUniqueID();
1526 LastSeenDIE = Die;
1527 return true;
1528}
1529
1530/// Get the child context of \a Context corresponding to \a DIE.
1531///
1532/// \returns the child context or null if we shouldn't track children
1533/// contexts. It also returns an additional bit meaning 'invalid'. An
1534/// invalid context means it shouldn't be considered for uniquing, but
1535/// its not returning null, because some children of that context
1536/// might be uniquing candidates.
1537/// FIXME: this is for dsymutil-classic compatibility, I don't think
1538/// it buys us much.
1539PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1540 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1541 NonRelocatableStringpool &StringPool) {
1542 unsigned Tag = DIE->getTag();
1543
1544 // FIXME: dsymutil-classic compat: We should bail out here if we
1545 // have a specification or an abstract_origin. We will get the
1546 // parent context wrong here.
1547
1548 switch (Tag) {
1549 default:
1550 // By default stop gathering child contexts.
1551 return PointerIntPair<DeclContext *, 1>(nullptr);
1552 case dwarf::DW_TAG_compile_unit:
1553 // FIXME: Add support for DW_TAG_module.
1554 return PointerIntPair<DeclContext *, 1>(&Context);
1555 case dwarf::DW_TAG_subprogram:
1556 // Do not unique anything inside CU local functions.
1557 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1558 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1559 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1560 dwarf::DW_AT_external, 0))
1561 return PointerIntPair<DeclContext *, 1>(nullptr);
1562 // Fallthrough
1563 case dwarf::DW_TAG_member:
1564 case dwarf::DW_TAG_namespace:
1565 case dwarf::DW_TAG_structure_type:
1566 case dwarf::DW_TAG_class_type:
1567 case dwarf::DW_TAG_union_type:
1568 case dwarf::DW_TAG_enumeration_type:
1569 case dwarf::DW_TAG_typedef:
1570 // Artificial things might be ambiguous, because they might be
1571 // created on demand. For example implicitely defined constructors
1572 // are ambiguous because of the way we identify contexts, and they
1573 // won't be generated everytime everywhere.
1574 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1575 dwarf::DW_AT_artificial, 0))
1576 return PointerIntPair<DeclContext *, 1>(nullptr);
1577 break;
1578 }
1579
1580 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1581 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1582 StringRef NameRef;
1583 StringRef ShortNameRef;
1584 StringRef FileRef;
1585
1586 if (Name)
1587 NameRef = StringPool.internString(Name);
1588 else if (Tag == dwarf::DW_TAG_namespace)
1589 // FIXME: For dsymutil-classic compatibility. I think uniquing
1590 // within anonymous namespaces is wrong. There is no ODR guarantee
1591 // there.
1592 NameRef = StringPool.internString("(anonymous namespace)");
1593
1594 if (ShortName && ShortName != Name)
1595 ShortNameRef = StringPool.internString(ShortName);
1596 else
1597 ShortNameRef = NameRef;
1598
1599 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1600 Tag != dwarf::DW_TAG_union_type &&
1601 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1602 return PointerIntPair<DeclContext *, 1>(nullptr);
1603
1604 std::string File;
1605 unsigned Line = 0;
1606 unsigned ByteSize = 0;
1607
1608 // Gather some discriminating data about the DeclContext we will be
1609 // creating: File, line number and byte size. This shouldn't be
1610 // necessary, because the ODR is just about names, but given that we
1611 // do some approximations with overloaded functions and anonymous
1612 // namespaces, use these additional data points to make the process safer.
1613 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1614 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1615 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1616 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1617 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1618 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1619 &U.getOrigUnit())) {
1620 // FIXME: dsymutil-classic compatibility. I'd rather not
1621 // unique anything in anonymous namespaces, but if we do, then
1622 // verify that the file and line correspond.
1623 if (!Name && Tag == dwarf::DW_TAG_namespace)
1624 FileNum = 1;
1625
1626 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1627 // instead of "" would allow more uniquing, but for now, do
1628 // it this way to match dsymutil-classic.
1629 if (LT->getFileNameByIndex(
1630 FileNum, "",
1631 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1632 File)) {
1633 Line = DIE->getAttributeValueAsUnsignedConstant(
1634 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1635#ifdef HAVE_REALPATH
1636 // Cache the resolved paths, because calling realpath is expansive.
1637 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1638 File = ResolvedPath;
1639 } else {
1640 char RealPath[PATH_MAX + 1];
1641 RealPath[PATH_MAX] = 0;
1642 if (::realpath(File.c_str(), RealPath))
1643 File = RealPath;
1644 U.setResolvedPath(FileNum, File);
1645 }
1646#endif
1647 FileRef = StringPool.internString(File);
1648 }
1649 }
1650 }
1651 }
1652
1653 if (!Line && NameRef.empty())
1654 return PointerIntPair<DeclContext *, 1>(nullptr);
1655
1656 // FIXME: dsymutil-classic compat won't unique the same type
1657 // presented once as a struct and once as a class. Use the Tag in
1658 // the fully qualified name hash to get the same effect.
1659 // We hash NameRef, which is the mangled name, in order to get most
1660 // overloaded functions resolvec correctly.
1661 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1662
1663 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1664 // use the filename.
1665 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1666 Hash = hash_combine(Hash, FileRef);
1667
1668 // Now look if this context already exists.
1669 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1670 auto ContextIter = Contexts.find(&Key);
1671
1672 if (ContextIter == Contexts.end()) {
1673 // The context wasn't found.
1674 bool Inserted;
1675 DeclContext *NewContext =
1676 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1677 Context, DIE, U.getUniqueID());
1678 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1679 assert(Inserted && "Failed to insert DeclContext");
1680 (void)Inserted;
1681 } else if (Tag != dwarf::DW_TAG_namespace &&
1682 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1683 // The context was found, but it is ambiguous with another context
1684 // in the same file. Mark it invalid.
1685 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1686 }
1687
1688 assert(ContextIter != Contexts.end());
1689 // FIXME: dsymutil-classic compatibility. Union types aren't
1690 // uniques, but their children might be.
1691 if ((Tag == dwarf::DW_TAG_subprogram &&
1692 Context.getTag() != dwarf::DW_TAG_structure_type &&
1693 Context.getTag() != dwarf::DW_TAG_class_type) ||
1694 (Tag == dwarf::DW_TAG_union_type))
1695 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1696
1697 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1698}
1699
Adrian Prantl3565af42015-09-14 16:46:10 +00001700bool DwarfLinker::DIECloner::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1701 DWARFUnit &U, AttributesInfo &Info) {
1702 // FIXME: a bit wasteful as the first getName might return the
Frederic Rissbce93ff2015-03-16 02:05:10 +00001703 // short name.
1704 if (!Info.MangledName &&
1705 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001706 Info.MangledNameOffset =
1707 Linker.StringPool.getStringOffset(Info.MangledName);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001708
1709 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001710 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001711
1712 return Info.Name || Info.MangledName;
1713}
1714
Frederic Riss1b9da422015-02-13 23:18:29 +00001715/// \brief Report a warning to the user, optionaly including
1716/// information about a specific \p DIE related to the warning.
1717void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001718 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001719 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001720 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001721 Context = CurrentDebugObject->getObjectFilename();
1722 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001723
Frederic Rissb9818322015-02-28 00:29:07 +00001724 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001725 return;
1726
1727 errs() << " in DIE:\n";
1728 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1729 6 /* Indent */);
1730}
1731
Frederic Rissc99ea202015-02-28 00:29:11 +00001732bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1733 if (Options.NoOutput)
1734 return true;
1735
Frederic Rissb52cf522015-02-28 00:42:37 +00001736 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001737 return Streamer->init(TheTriple, OutputFilename);
1738}
1739
Frederic Riss563cba62015-01-28 22:15:14 +00001740/// \brief Recursive helper to gather the child->parent relationships in the
1741/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001742static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
Frederic Riss1c650942015-07-21 22:41:43 +00001743 unsigned ParentIdx, CompileUnit &CU,
1744 DeclContext *CurrentDeclContext,
1745 NonRelocatableStringpool &StringPool,
1746 DeclContextTree &Contexts) {
Frederic Riss563cba62015-01-28 22:15:14 +00001747 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001748 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1749
1750 Info.ParentIdx = ParentIdx;
1751 if (CU.hasODR()) {
1752 if (CurrentDeclContext) {
1753 auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1754 DIE, CU, StringPool);
1755 CurrentDeclContext = PtrInvalidPair.getPointer();
1756 Info.Ctxt =
1757 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1758 } else
1759 Info.Ctxt = CurrentDeclContext = nullptr;
1760 }
Frederic Riss563cba62015-01-28 22:15:14 +00001761
1762 if (DIE->hasChildren())
1763 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1764 Child = Child->getSibling())
Frederic Riss1c650942015-07-21 22:41:43 +00001765 gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1766 Contexts);
Frederic Riss563cba62015-01-28 22:15:14 +00001767}
1768
Frederic Riss84c09a52015-02-13 23:18:34 +00001769static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1770 switch (Tag) {
1771 default:
1772 return false;
1773 case dwarf::DW_TAG_subprogram:
1774 case dwarf::DW_TAG_lexical_block:
1775 case dwarf::DW_TAG_subroutine_type:
1776 case dwarf::DW_TAG_structure_type:
1777 case dwarf::DW_TAG_class_type:
1778 case dwarf::DW_TAG_union_type:
1779 return true;
1780 }
1781 llvm_unreachable("Invalid Tag");
1782}
1783
Frederic Riss1c650942015-07-21 22:41:43 +00001784static unsigned getRefAddrSize(const DWARFUnit &U) {
1785 if (U.getVersion() == 2)
1786 return U.getAddressByteSize();
1787 return 4;
1788}
1789
Frederic Riss63786b02015-03-15 20:45:43 +00001790void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001791 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss63786b02015-03-15 20:45:43 +00001792 // Iterate over the debug map entries and put all the ones that are
1793 // functions (because they have a size) into the Ranges map. This
1794 // map is very similar to the FunctionRanges that are stored in each
1795 // unit, with 2 notable differences:
1796 // - obviously this one is global, while the other ones are per-unit.
1797 // - this one contains not only the functions described in the DIE
1798 // tree, but also the ones that are only in the debug map.
1799 // The latter information is required to reproduce dsymutil's logic
1800 // while linking line tables. The cases where this information
1801 // matters look like bugs that need to be investigated, but for now
1802 // we need to reproduce dsymutil's behavior.
1803 // FIXME: Once we understood exactly if that information is needed,
1804 // maybe totally remove this (or try to use it to do a real
1805 // -gline-tables-only on Darwin.
1806 for (const auto &Entry : Obj.symbols()) {
1807 const auto &Mapping = Entry.getValue();
1808 if (Mapping.Size)
1809 Ranges[Mapping.ObjectAddress] = std::make_pair(
1810 Mapping.ObjectAddress + Mapping.Size,
1811 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1812 }
Frederic Riss563cba62015-01-28 22:15:14 +00001813}
1814
Frederic Riss1036e642015-02-13 23:18:22 +00001815void DwarfLinker::endDebugObject() {
1816 Units.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001817 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001818
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001819 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1820 (*I)->~DIEBlock();
1821 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1822 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001823
1824 DIEBlocks.clear();
1825 DIELocs.clear();
1826 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001827}
1828
1829/// \brief Iterate over the relocations of the given \p Section and
1830/// store the ones that correspond to debug map entries into the
1831/// ValidRelocs array.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001832void DwarfLinker::RelocationManager::
1833findValidRelocsMachO(const object::SectionRef &Section,
1834 const object::MachOObjectFile &Obj,
1835 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001836 StringRef Contents;
1837 Section.getContents(Contents);
1838 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1839
1840 for (const object::RelocationRef &Reloc : Section.relocations()) {
1841 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1842 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1843 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001844 uint64_t Offset64 = Reloc.getOffset();
1845 if ((RelocSize != 4 && RelocSize != 8)) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001846 Linker.reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001847 continue;
1848 }
1849 uint32_t Offset = Offset64;
1850 // Mach-o uses REL relocations, the addend is at the relocation offset.
1851 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1852
1853 auto Sym = Reloc.getSymbol();
1854 if (Sym != Obj.symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001855 ErrorOr<StringRef> SymbolName = Sym->getName();
1856 if (!SymbolName) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001857 Linker.reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001858 continue;
1859 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001860 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001861 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1862 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1863 // Do not store the addend. The addend was the address of the
1864 // symbol in the object file, the address in the binary that is
1865 // stored in the debug map doesn't need to be offseted.
1866 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1867 }
1868 }
1869}
1870
1871/// \brief Dispatch the valid relocation finding logic to the
1872/// appropriate handler depending on the object file format.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001873bool DwarfLinker::RelocationManager::findValidRelocs(
1874 const object::SectionRef &Section, const object::ObjectFile &Obj,
1875 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001876 // Dispatch to the right handler depending on the file type.
1877 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1878 findValidRelocsMachO(Section, *MachOObj, DMO);
1879 else
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001880 Linker.reportWarning(Twine("unsupported object file type: ") +
1881 Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001882
1883 if (ValidRelocs.empty())
1884 return false;
1885
1886 // Sort the relocations by offset. We will walk the DIEs linearly in
1887 // the file, this allows us to just keep an index in the relocation
1888 // array that we advance during our walk, rather than resorting to
1889 // some associative container. See DwarfLinker::NextValidReloc.
1890 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1891 return true;
1892}
1893
1894/// \brief Look for relocations in the debug_info section that match
1895/// entries in the debug map. These relocations will drive the Dwarf
1896/// link by indicating which DIEs refer to symbols present in the
1897/// linked binary.
1898/// \returns wether there are any valid relocations in the debug info.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001899bool DwarfLinker::RelocationManager::
1900findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1901 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001902 // Find the debug_info section.
1903 for (const object::SectionRef &Section : Obj.sections()) {
1904 StringRef SectionName;
1905 Section.getName(SectionName);
1906 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1907 if (SectionName != "debug_info")
1908 continue;
1909 return findValidRelocs(Section, Obj, DMO);
1910 }
1911 return false;
1912}
Frederic Riss563cba62015-01-28 22:15:14 +00001913
Frederic Riss84c09a52015-02-13 23:18:34 +00001914/// \brief Checks that there is a relocation against an actual debug
1915/// map entry between \p StartOffset and \p NextOffset.
1916///
1917/// This function must be called with offsets in strictly ascending
1918/// order because it never looks back at relocations it already 'went past'.
1919/// \returns true and sets Info.InDebugMap if it is the case.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001920bool DwarfLinker::RelocationManager::
1921hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1922 CompileUnit::DIEInfo &Info) {
Frederic Riss84c09a52015-02-13 23:18:34 +00001923 assert(NextValidReloc == 0 ||
1924 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1925 if (NextValidReloc >= ValidRelocs.size())
1926 return false;
1927
1928 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1929
1930 // We might need to skip some relocs that we didn't consider. For
1931 // example the high_pc of a discarded DIE might contain a reloc that
1932 // is in the list because it actually corresponds to the start of a
1933 // function that is in the debug map.
1934 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1935 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1936
1937 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1938 return false;
1939
1940 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001941 const auto &Mapping = ValidReloc.Mapping->getValue();
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001942 if (Linker.Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001943 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1944 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001945 uint64_t(Mapping.ObjectAddress),
1946 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001947
Frederic Rissf37964c2015-06-05 20:27:07 +00001948 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1949 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001950 Info.InDebugMap = true;
1951 return true;
1952}
1953
1954/// \brief Get the starting and ending (exclusive) offset for the
1955/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1956/// supposed to point to the position of the first attribute described
1957/// by \p Abbrev.
1958/// \return [StartOffset, EndOffset) as a pair.
1959static std::pair<uint32_t, uint32_t>
1960getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1961 unsigned Offset, const DWARFUnit &Unit) {
1962 DataExtractor Data = Unit.getDebugInfoExtractor();
1963
1964 for (unsigned i = 0; i < Idx; ++i)
1965 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1966
1967 uint32_t End = Offset;
1968 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1969
1970 return std::make_pair(Offset, End);
1971}
1972
1973/// \brief Check if a variable describing DIE should be kept.
1974/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001975unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
1976 const DWARFDebugInfoEntryMinimal &DIE,
1977 CompileUnit &Unit,
1978 CompileUnit::DIEInfo &MyInfo,
1979 unsigned Flags) {
Frederic Riss84c09a52015-02-13 23:18:34 +00001980 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1981
1982 // Global variables with constant value can always be kept.
1983 if (!(Flags & TF_InFunctionScope) &&
1984 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1985 MyInfo.InDebugMap = true;
1986 return Flags | TF_Keep;
1987 }
1988
1989 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1990 if (LocationIdx == -1U)
1991 return Flags;
1992
1993 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1994 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1995 uint32_t LocationOffset, LocationEndOffset;
1996 std::tie(LocationOffset, LocationEndOffset) =
1997 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1998
1999 // See if there is a relocation to a valid debug map entry inside
2000 // this variable's location. The order is important here. We want to
2001 // always check in the variable has a valid relocation, so that the
2002 // DIEInfo is filled. However, we don't want a static variable in a
2003 // function to force us to keep the enclosing function.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002004 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
Frederic Riss84c09a52015-02-13 23:18:34 +00002005 (Flags & TF_InFunctionScope))
2006 return Flags;
2007
Frederic Rissb9818322015-02-28 00:29:07 +00002008 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002009 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2010
2011 return Flags | TF_Keep;
2012}
2013
2014/// \brief Check if a function describing DIE should be kept.
2015/// \returns updated TraversalFlags.
2016unsigned DwarfLinker::shouldKeepSubprogramDIE(
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002017 RelocationManager &RelocMgr,
Frederic Riss84c09a52015-02-13 23:18:34 +00002018 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2019 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2020 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2021
2022 Flags |= TF_InFunctionScope;
2023
2024 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2025 if (LowPcIdx == -1U)
2026 return Flags;
2027
2028 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2029 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2030 uint32_t LowPcOffset, LowPcEndOffset;
2031 std::tie(LowPcOffset, LowPcEndOffset) =
2032 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2033
2034 uint64_t LowPc =
2035 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2036 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2037 if (LowPc == -1ULL ||
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002038 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
Frederic Riss84c09a52015-02-13 23:18:34 +00002039 return Flags;
2040
Frederic Rissb9818322015-02-28 00:29:07 +00002041 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002042 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2043
Frederic Riss1af75f72015-03-12 18:45:10 +00002044 Flags |= TF_Keep;
2045
2046 DWARFFormValue HighPcValue;
2047 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2048 reportWarning("Function without high_pc. Range will be discarded.\n",
2049 &OrigUnit, &DIE);
2050 return Flags;
2051 }
2052
2053 uint64_t HighPc;
2054 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2055 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2056 } else {
2057 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2058 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2059 }
2060
Frederic Riss63786b02015-03-15 20:45:43 +00002061 // Replace the debug map range with a more accurate one.
2062 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002063 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2064 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002065}
2066
2067/// \brief Check if a DIE should be kept.
2068/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002069unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2070 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00002071 CompileUnit &Unit,
2072 CompileUnit::DIEInfo &MyInfo,
2073 unsigned Flags) {
2074 switch (DIE.getTag()) {
2075 case dwarf::DW_TAG_constant:
2076 case dwarf::DW_TAG_variable:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002077 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002078 case dwarf::DW_TAG_subprogram:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002079 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002080 case dwarf::DW_TAG_module:
2081 case dwarf::DW_TAG_imported_module:
2082 case dwarf::DW_TAG_imported_declaration:
2083 case dwarf::DW_TAG_imported_unit:
2084 // We always want to keep these.
2085 return Flags | TF_Keep;
2086 }
2087
2088 return Flags;
2089}
2090
Frederic Riss84c09a52015-02-13 23:18:34 +00002091/// \brief Mark the passed DIE as well as all the ones it depends on
2092/// as kept.
2093///
2094/// This function is called by lookForDIEsToKeep on DIEs that are
2095/// newly discovered to be needed in the link. It recursively calls
2096/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2097/// TraversalFlags to inform it that it's not doing the primary DIE
2098/// tree walk.
Adrian Prantl6ec47122015-09-22 15:31:14 +00002099void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002100 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002101 CompileUnit::DIEInfo &MyInfo,
2102 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002103 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002104 const DWARFUnit &Unit = CU.getOrigUnit();
2105 MyInfo.Keep = true;
2106
2107 // First mark all the parent chain as kept.
2108 unsigned AncestorIdx = MyInfo.ParentIdx;
2109 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002110 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002111 lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002112 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002113 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2114 }
2115
2116 // Then we need to mark all the DIEs referenced by this DIE's
2117 // attributes as kept.
2118 DataExtractor Data = Unit.getDebugInfoExtractor();
Frederic Riss36c3cb82015-09-11 04:17:25 +00002119 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2120 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
Frederic Riss84c09a52015-02-13 23:18:34 +00002121
2122 // Mark all DIEs referenced through atttributes as kept.
2123 for (const auto &AttrSpec : Abbrev->attributes()) {
2124 DWARFFormValue Val(AttrSpec.Form);
2125
2126 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2127 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2128 continue;
2129 }
2130
2131 Val.extractValue(Data, &Offset, &Unit);
2132 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002133 if (const auto *RefDIE =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002134 resolveDIEReference(*this, MutableArrayRef<CompileUnit>(Units), Val,
2135 Unit, Die, ReferencedCU)) {
Frederic Riss1c650942015-07-21 22:41:43 +00002136 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2137 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2138 // If the referenced DIE has a DeclContext that has already been
2139 // emitted, then do not keep the one in this CU. We'll link to
2140 // the canonical DIE in cloneDieReferenceAttribute.
2141 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2142 // be necessary and could be advantageously replaced by
2143 // ReferencedCU->hasODR() && CU.hasODR().
2144 // FIXME: compatibility with dsymutil-classic. There is no
2145 // reason not to unique ref_addr references.
2146 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2147 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2148 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2149 continue;
2150
2151 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002152 lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002153 TF_Keep | TF_DependencyWalk | ODRFlag);
2154 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002155 }
2156}
2157
2158/// \brief Recursively walk the \p DIE tree and look for DIEs to
2159/// keep. Store that information in \p CU's DIEInfo.
2160///
2161/// This function is the entry point of the DIE selection
2162/// algorithm. It is expected to walk the DIE tree in file order and
2163/// (though the mediation of its helper) call hasValidRelocation() on
2164/// each DIE that might be a 'root DIE' (See DwarfLinker class
2165/// comment).
2166/// While walking the dependencies of root DIEs, this function is
2167/// also called, but during these dependency walks the file order is
2168/// not respected. The TF_DependencyWalk flag tells us which kind of
2169/// traversal we are currently doing.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002170void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2171 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002172 const DebugMapObject &DMO, CompileUnit &CU,
2173 unsigned Flags) {
Frederic Riss36c3cb82015-09-11 04:17:25 +00002174 unsigned Idx = CU.getOrigUnit().getDIEIndex(&Die);
Frederic Riss84c09a52015-02-13 23:18:34 +00002175 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2176 bool AlreadyKept = MyInfo.Keep;
2177
2178 // If the Keep flag is set, we are marking a required DIE's
2179 // dependencies. If our target is already marked as kept, we're all
2180 // set.
2181 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2182 return;
2183
Adrian Prantl6ec47122015-09-22 15:31:14 +00002184 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
Frederic Riss84c09a52015-02-13 23:18:34 +00002185 // because it would screw up the relocation finding logic.
2186 if (!(Flags & TF_DependencyWalk))
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002187 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002188
2189 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002190 if (!AlreadyKept && (Flags & TF_Keep)) {
2191 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
Adrian Prantl6ec47122015-09-22 15:31:14 +00002192 keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
Frederic Riss1c650942015-07-21 22:41:43 +00002193 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002194 // The TF_ParentWalk flag tells us that we are currently walking up
2195 // the parent chain of a required DIE, and we don't want to mark all
2196 // the children of the parents as kept (consider for example a
2197 // DW_TAG_namespace node in the parent chain). There are however a
2198 // set of DIE types for which we want to ignore that directive and still
2199 // walk their children.
Frederic Riss36c3cb82015-09-11 04:17:25 +00002200 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
Frederic Riss84c09a52015-02-13 23:18:34 +00002201 Flags &= ~TF_ParentWalk;
2202
Frederic Riss36c3cb82015-09-11 04:17:25 +00002203 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
Frederic Riss84c09a52015-02-13 23:18:34 +00002204 return;
2205
Frederic Riss36c3cb82015-09-11 04:17:25 +00002206 for (auto *Child = Die.getFirstChild(); Child && !Child->isNULL();
Frederic Riss84c09a52015-02-13 23:18:34 +00002207 Child = Child->getSibling())
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002208 lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002209}
2210
Frederic Rissb8b43d52015-03-04 22:07:44 +00002211/// \brief Assign an abbreviation numer to \p Abbrev.
2212///
2213/// Our DIEs get freed after every DebugMapObject has been processed,
2214/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2215/// the instances hold by the DIEs. When we encounter an abbreviation
2216/// that we don't know, we create a permanent copy of it.
2217void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2218 // Check the set for priors.
2219 FoldingSetNodeID ID;
2220 Abbrev.Profile(ID);
2221 void *InsertToken;
2222 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2223
2224 // If it's newly added.
2225 if (InSet) {
2226 // Assign existing abbreviation number.
2227 Abbrev.setNumber(InSet->getNumber());
2228 } else {
2229 // Add to abbreviation list.
2230 Abbreviations.push_back(
2231 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2232 for (const auto &Attr : Abbrev.getData())
2233 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2234 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2235 // Assign the unique abbreviation number.
2236 Abbrev.setNumber(Abbreviations.size());
2237 Abbreviations.back()->setNumber(Abbreviations.size());
2238 }
2239}
2240
Adrian Prantl3565af42015-09-14 16:46:10 +00002241unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2242 AttributeSpec AttrSpec,
2243 const DWARFFormValue &Val,
2244 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002245 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002246 const char *String = *Val.getAsCString(&U);
Adrian Prantl3565af42015-09-14 16:46:10 +00002247 unsigned Offset = Linker.StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002248 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002249 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002250 return 4;
2251}
2252
Adrian Prantl3565af42015-09-14 16:46:10 +00002253unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
Frederic Riss9833de62015-03-06 23:22:53 +00002254 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2255 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002256 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002257 const DWARFUnit &U = Unit.getOrigUnit();
2258 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002259 DIE *NewRefDie = nullptr;
2260 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002261 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002262
Frederic Riss1c650942015-07-21 22:41:43 +00002263 const DWARFDebugInfoEntryMinimal *RefDie =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002264 resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE, RefUnit);
Frederic Riss1c650942015-07-21 22:41:43 +00002265
2266 // If the referenced DIE is not found, drop the attribute.
2267 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002268 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002269
2270 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2271 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002272
2273 // If we already have emitted an equivalent DeclContext, just point
2274 // at it.
2275 if (isODRAttribute(AttrSpec.Attr)) {
2276 Ctxt = RefInfo.Ctxt;
2277 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2278 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2279 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2280 dwarf::DW_FORM_ref_addr, Attr);
2281 return getRefAddrSize(U);
2282 }
2283 }
2284
Frederic Riss9833de62015-03-06 23:22:53 +00002285 if (!RefInfo.Clone) {
2286 assert(Ref > InputDIE.getOffset());
2287 // We haven't cloned this DIE yet. Just create an empty one and
2288 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002289 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002290 }
2291 NewRefDie = RefInfo.Clone;
2292
Frederic Riss1c650942015-07-21 22:41:43 +00002293 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2294 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002295 // We cannot currently rely on a DIEEntry to emit ref_addr
2296 // references, because the implementation calls back to DwarfDebug
2297 // to find the unit offset. (We don't have a DwarfDebug)
2298 // FIXME: we should be able to design DIEEntry reliance on
2299 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002300 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002301 if (Ref < InputDIE.getOffset()) {
2302 // We must have already cloned that DIE.
2303 uint32_t NewRefOffset =
2304 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002305 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002306 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2307 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002308 } else {
2309 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002310 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002311 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002312 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002313 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2314 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002315 }
Frederic Riss1c650942015-07-21 22:41:43 +00002316 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002317 }
2318
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002319 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2320 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002321 return AttrSize;
2322}
2323
Adrian Prantl3565af42015-09-14 16:46:10 +00002324unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2325 AttributeSpec AttrSpec,
2326 const DWARFFormValue &Val,
2327 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002328 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002329 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002330 DIELoc *Loc = nullptr;
2331 DIEBlock *Block = nullptr;
2332 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002333 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002334 Loc = new (DIEAlloc) DIELoc;
Adrian Prantl3565af42015-09-14 16:46:10 +00002335 Linker.DIELocs.push_back(Loc);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002336 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002337 Block = new (DIEAlloc) DIEBlock;
Adrian Prantl3565af42015-09-14 16:46:10 +00002338 Linker.DIEBlocks.push_back(Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002339 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002340 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2341 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002342
2343 if (Loc)
2344 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2345 dwarf::Form(AttrSpec.Form), Loc);
2346 else
2347 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2348 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002349 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2350 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002351 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2352 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002353 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2354 // the DIE class, this if could be replaced by
2355 // Attr->setSize(Bytes.size()).
Adrian Prantl3565af42015-09-14 16:46:10 +00002356 if (Linker.Streamer) {
2357 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002358 if (Loc)
Adrian Prantl3565af42015-09-14 16:46:10 +00002359 Loc->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002360 else
Adrian Prantl3565af42015-09-14 16:46:10 +00002361 Block->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002362 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002363 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002364 return AttrSize;
2365}
2366
Adrian Prantl3565af42015-09-14 16:46:10 +00002367unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2368 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2369 const CompileUnit &Unit, AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002370 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002371 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2372 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2373 Die.getTag() == dwarf::DW_TAG_lexical_block)
Frederic Riss7b5563a2015-08-31 01:43:14 +00002374 // The low_pc of a block or inline subroutine might get
2375 // relocated because it happens to match the low_pc of the
2376 // enclosing subprogram. To prevent issues with that, always use
2377 // the low_pc from the input DIE if relocations have been applied.
2378 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2379 Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002380 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2381 Addr = Unit.getLowPc();
2382 if (Addr == UINT64_MAX)
2383 return 0;
2384 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002385 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002386 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002387 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2388 if (uint64_t HighPc = Unit.getHighPc())
2389 Addr = HighPc;
2390 else
2391 return 0;
2392 } else
2393 // If we have a high_pc recorded for the input DIE, use
2394 // it. Otherwise (when no relocations where applied) just use the
2395 // one we just decoded.
2396 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002397 }
2398
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002399 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002400 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002401 return Unit.getOrigUnit().getAddressByteSize();
2402}
2403
Adrian Prantl3565af42015-09-14 16:46:10 +00002404unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002405 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002406 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002407 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002408 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002409 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2410 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2411 if (Unit.getLowPc() == -1ULL)
2412 return 0;
2413 // Dwarf >= 4 high_pc is an size, not an address.
2414 Value = Unit.getHighPc() - Unit.getLowPc();
2415 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002416 Value = *Val.getAsSectionOffset();
2417 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2418 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002419 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2420 Value = *OptionalValue;
2421 else {
Adrian Prantl3565af42015-09-14 16:46:10 +00002422 Linker.reportWarning(
2423 "Unsupported scalar attribute form. Dropping attribute.",
2424 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002425 return 0;
2426 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002427 PatchLocation Patch =
2428 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2429 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002430 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002431 Unit.noteRangeAttribute(Die, Patch);
Frederic Riss29eedc72015-09-11 04:17:30 +00002432
Frederic Rissdfb97902015-03-14 15:49:07 +00002433 // A more generic way to check for location attributes would be
2434 // nice, but it's very unlikely that any other attribute needs a
2435 // location list.
2436 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2437 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002438 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002439 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2440 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002441
Frederic Rissb8b43d52015-03-04 22:07:44 +00002442 return AttrSize;
2443}
2444
2445/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2446/// value \p Val, and add it to \p Die.
2447/// \returns the size of the cloned attribute.
Adrian Prantl3565af42015-09-14 16:46:10 +00002448unsigned DwarfLinker::DIECloner::cloneAttribute(
2449 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2450 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2451 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002452 const DWARFUnit &U = Unit.getOrigUnit();
2453
2454 switch (AttrSpec.Form) {
2455 case dwarf::DW_FORM_strp:
2456 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002457 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002458 case dwarf::DW_FORM_ref_addr:
2459 case dwarf::DW_FORM_ref1:
2460 case dwarf::DW_FORM_ref2:
2461 case dwarf::DW_FORM_ref4:
2462 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002463 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002464 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002465 case dwarf::DW_FORM_block:
2466 case dwarf::DW_FORM_block1:
2467 case dwarf::DW_FORM_block2:
2468 case dwarf::DW_FORM_block4:
2469 case dwarf::DW_FORM_exprloc:
2470 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2471 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002472 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002473 case dwarf::DW_FORM_data1:
2474 case dwarf::DW_FORM_data2:
2475 case dwarf::DW_FORM_data4:
2476 case dwarf::DW_FORM_data8:
2477 case dwarf::DW_FORM_udata:
2478 case dwarf::DW_FORM_sdata:
2479 case dwarf::DW_FORM_sec_offset:
2480 case dwarf::DW_FORM_flag:
2481 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002482 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2483 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002484 default:
Adrian Prantl3565af42015-09-14 16:46:10 +00002485 Linker.reportWarning(
2486 "Unsupported attribute form in cloneAttribute. Dropping.", &U,
2487 &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002488 }
2489
2490 return 0;
2491}
2492
Frederic Riss23e20e92015-03-07 01:25:09 +00002493/// \brief Apply the valid relocations found by findValidRelocs() to
2494/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2495/// in the debug_info section.
2496///
2497/// Like for findValidRelocs(), this function must be called with
2498/// monotonic \p BaseOffset values.
2499///
2500/// \returns wether any reloc has been applied.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002501bool DwarfLinker::RelocationManager::
2502applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2503 bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002504 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002505 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2506 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002507 if (NextValidReloc >= ValidRelocs.size())
2508 return false;
2509
2510 // Skip relocs that haven't been applied.
2511 while (NextValidReloc < ValidRelocs.size() &&
2512 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2513 ++NextValidReloc;
2514
2515 bool Applied = false;
2516 uint64_t EndOffset = BaseOffset + Data.size();
2517 while (NextValidReloc < ValidRelocs.size() &&
2518 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2519 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2520 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2521 assert(ValidReloc.Offset - BaseOffset < Data.size());
2522 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2523 char Buf[8];
2524 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2525 Value += ValidReloc.Addend;
2526 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2527 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2528 Buf[i] = uint8_t(Value >> (Index * 8));
2529 }
2530 assert(ValidReloc.Size <= sizeof(Buf));
2531 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2532 Applied = true;
2533 }
2534
2535 return Applied;
2536}
2537
Frederic Rissbce93ff2015-03-16 02:05:10 +00002538static bool isTypeTag(uint16_t Tag) {
2539 switch (Tag) {
2540 case dwarf::DW_TAG_array_type:
2541 case dwarf::DW_TAG_class_type:
2542 case dwarf::DW_TAG_enumeration_type:
2543 case dwarf::DW_TAG_pointer_type:
2544 case dwarf::DW_TAG_reference_type:
2545 case dwarf::DW_TAG_string_type:
2546 case dwarf::DW_TAG_structure_type:
2547 case dwarf::DW_TAG_subroutine_type:
2548 case dwarf::DW_TAG_typedef:
2549 case dwarf::DW_TAG_union_type:
2550 case dwarf::DW_TAG_ptr_to_member_type:
2551 case dwarf::DW_TAG_set_type:
2552 case dwarf::DW_TAG_subrange_type:
2553 case dwarf::DW_TAG_base_type:
2554 case dwarf::DW_TAG_const_type:
2555 case dwarf::DW_TAG_constant:
2556 case dwarf::DW_TAG_file_type:
2557 case dwarf::DW_TAG_namelist:
2558 case dwarf::DW_TAG_packed_type:
2559 case dwarf::DW_TAG_volatile_type:
2560 case dwarf::DW_TAG_restrict_type:
2561 case dwarf::DW_TAG_interface_type:
2562 case dwarf::DW_TAG_unspecified_type:
2563 case dwarf::DW_TAG_shared_type:
2564 return true;
2565 default:
2566 break;
2567 }
2568 return false;
2569}
2570
Frederic Riss29eedc72015-09-11 04:17:30 +00002571static bool
2572shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2573 uint16_t Tag, bool InDebugMap, bool SkipPC,
2574 bool InFunctionScope) {
2575 switch (AttrSpec.Attr) {
2576 default:
2577 return false;
2578 case dwarf::DW_AT_low_pc:
2579 case dwarf::DW_AT_high_pc:
2580 case dwarf::DW_AT_ranges:
2581 return SkipPC;
2582 case dwarf::DW_AT_location:
2583 case dwarf::DW_AT_frame_base:
2584 // FIXME: for some reason dsymutil-classic keeps the location
2585 // attributes when they are of block type (ie. not location
2586 // lists). This is totally wrong for globals where we will keep a
2587 // wrong address. It is mostly harmless for locals, but there is
2588 // no point in keeping these anyway when the function wasn't linked.
2589 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2590 !InDebugMap)) &&
2591 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2592 }
2593}
2594
Adrian Prantl3565af42015-09-14 16:46:10 +00002595DIE *DwarfLinker::DIECloner::cloneDIE(
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002596 const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2597 int64_t PCOffset, uint32_t OutOffset, unsigned Flags) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002598 DWARFUnit &U = Unit.getOrigUnit();
2599 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002600 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002601
2602 // Should the DIE appear in the output?
2603 if (!Unit.getInfo(Idx).Keep)
2604 return nullptr;
2605
2606 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002607 // The DIE might have been already created by a forward reference
2608 // (see cloneDieReferenceAttribute()).
2609 DIE *Die = Info.Clone;
2610 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002611 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002612 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002613 Die->setOffset(OutOffset);
Frederic Riss1c650942015-07-21 22:41:43 +00002614 if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2615 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2616 !Info.Ctxt->getCanonicalDIEOffset()) {
2617 // We are about to emit a DIE that is the root of its own valid
2618 // DeclContext tree. Make the current offset the canonical offset
2619 // for this context.
2620 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2621 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002622
2623 // Extract and clone every attribute.
2624 DataExtractor Data = U.getDebugInfoExtractor();
Adrian Prantle5162db2015-09-22 22:20:50 +00002625 // Point to the next DIE (generally there is always at least a NULL
2626 // entry after the current one). If this is a lone
2627 // DW_TAG_compile_unit without any children, point to the next unit.
2628 uint32_t NextOffset =
2629 (Idx + 1 < U.getNumDIEs())
2630 ? U.getDIEAtIndex(Idx + 1)->getOffset()
2631 : U.getNextUnitOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002632 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002633
2634 // We could copy the data only if we need to aply a relocation to
2635 // it. After testing, it seems there is no performance downside to
2636 // doing the copy unconditionally, and it makes the code simpler.
2637 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2638 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2639 // Modify the copy with relocated addresses.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002640 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
Frederic Riss31da3242015-03-11 18:45:52 +00002641 // If we applied relocations, we store the value of high_pc that was
2642 // potentially stored in the input DIE. If high_pc is an address
2643 // (Dwarf version == 2), then it might have been relocated to a
2644 // totally unrelated value (because the end address in the object
2645 // file might be start address of another function which got moved
2646 // independantly by the linker). The computation of the actual
2647 // high_pc value is done in cloneAddressAttribute().
2648 AttrInfo.OrigHighPc =
2649 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
Frederic Riss7b5563a2015-08-31 01:43:14 +00002650 // Also store the low_pc. It might get relocated in an
2651 // inline_subprogram that happens at the beginning of its
2652 // inlining function.
2653 AttrInfo.OrigLowPc =
2654 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
Frederic Riss31da3242015-03-11 18:45:52 +00002655 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002656
2657 // Reset the Offset to 0 as we will be working on the local copy of
2658 // the data.
2659 Offset = 0;
2660
Frederic Rissb8b43d52015-03-04 22:07:44 +00002661 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2662 Offset += getULEB128Size(Abbrev->getCode());
2663
Frederic Riss31da3242015-03-11 18:45:52 +00002664 // We are entering a subprogram. Get and propagate the PCOffset.
2665 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2666 PCOffset = Info.AddrAdjust;
2667 AttrInfo.PCOffset = PCOffset;
2668
Frederic Riss29eedc72015-09-11 04:17:30 +00002669 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2670 Flags |= TF_InFunctionScope;
2671 if (!Info.InDebugMap)
2672 Flags |= TF_SkipPC;
2673 }
2674
2675 bool Copied = false;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002676 for (const auto &AttrSpec : Abbrev->attributes()) {
Frederic Riss29eedc72015-09-11 04:17:30 +00002677 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2678 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2679 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2680 // FIXME: dsymutil-classic keeps the old abbreviation around
2681 // even if it's not used. We can remove this (and the copyAbbrev
2682 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2683 if (!Copied) {
2684 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2685 Copied = true;
2686 }
2687 continue;
2688 }
2689
Frederic Rissb8b43d52015-03-04 22:07:44 +00002690 DWARFFormValue Val(AttrSpec.Form);
2691 uint32_t AttrSize = Offset;
2692 Val.extractValue(Data, &Offset, &U);
2693 AttrSize = Offset - AttrSize;
2694
Frederic Riss31da3242015-03-11 18:45:52 +00002695 OutOffset +=
2696 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002697 }
2698
Frederic Rissbce93ff2015-03-16 02:05:10 +00002699 // Look for accelerator entries.
2700 uint16_t Tag = InputDIE.getTag();
2701 // FIXME: This is slightly wrong. An inline_subroutine without a
2702 // low_pc, but with AT_ranges might be interesting to get into the
2703 // accelerator tables too. For now stick with dsymutil's behavior.
2704 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2705 Tag != dwarf::DW_TAG_compile_unit &&
2706 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2707 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2708 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2709 AttrInfo.MangledNameOffset,
2710 Tag == dwarf::DW_TAG_inlined_subroutine);
2711 if (AttrInfo.Name)
2712 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2713 Tag == dwarf::DW_TAG_inlined_subroutine);
2714 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2715 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2716 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2717 }
2718
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002719 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002720 // If a scope DIE is kept, we must have kept at least one child. If
2721 // it's not the case, we'll just be emitting one wasteful end of
2722 // children marker, but things won't break.
2723 if (InputDIE.hasChildren())
2724 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2725 // Assign a permanent abbrev number
Adrian Prantl3565af42015-09-14 16:46:10 +00002726 Linker.AssignAbbrev(NewAbbrev);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002727 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002728
2729 // Add the size of the abbreviation number to the output offset.
2730 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2731
2732 if (!Abbrev->hasChildren()) {
2733 // Update our size.
2734 Die->setSize(OutOffset - Die->getOffset());
2735 return Die;
2736 }
2737
2738 // Recursively clone children.
2739 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2740 Child = Child->getSibling()) {
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002741 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset, Flags)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002742 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002743 OutOffset = Clone->getOffset() + Clone->getSize();
2744 }
2745 }
2746
2747 // Account for the end of children marker.
2748 OutOffset += sizeof(int8_t);
2749 // Update our size.
2750 Die->setSize(OutOffset - Die->getOffset());
2751 return Die;
2752}
2753
Frederic Riss25440872015-03-13 23:30:31 +00002754/// \brief Patch the input object file relevant debug_ranges entries
2755/// and emit them in the output file. Update the relevant attributes
2756/// to point at the new entries.
2757void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2758 DWARFContext &OrigDwarf) const {
2759 DWARFDebugRangeList RangeList;
2760 const auto &FunctionRanges = Unit.getFunctionRanges();
2761 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2762 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2763 OrigDwarf.isLittleEndian(), AddressSize);
2764 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2765 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002766 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002767 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2768 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2769 // Ranges addresses are based on the unit's low_pc. Compute the
2770 // offset we need to apply to adapt to the the new unit's low_pc.
2771 int64_t UnitPcOffset = 0;
2772 if (OrigLowPc != -1ULL)
2773 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2774
2775 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002776 uint32_t Offset = RangeAttribute.get();
2777 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002778 RangeList.extract(RangeExtractor, &Offset);
2779 const auto &Entries = RangeList.getEntries();
Frederic Riss94546202015-08-31 05:09:32 +00002780 if (!Entries.empty()) {
2781 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
Frederic Riss25440872015-03-13 23:30:31 +00002782
Frederic Riss25440872015-03-13 23:30:31 +00002783 if (CurrRange == InvalidRange ||
Frederic Riss94546202015-08-31 05:09:32 +00002784 First.StartAddress + OrigLowPc < CurrRange.start() ||
2785 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2786 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2787 if (CurrRange == InvalidRange ||
2788 CurrRange.start() > First.StartAddress + OrigLowPc) {
2789 reportWarning("no mapping for range.");
2790 continue;
2791 }
Frederic Riss25440872015-03-13 23:30:31 +00002792 }
2793 }
2794
2795 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2796 AddressSize);
2797 }
2798}
2799
Frederic Riss563b1b02015-03-14 03:46:51 +00002800/// \brief Generate the debug_aranges entries for \p Unit and if the
2801/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2802/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002803/// FIXME: this could actually be done right in patchRangesForUnit,
2804/// but for the sake of initial bit-for-bit compatibility with legacy
2805/// dsymutil, we have to do it in a delayed pass.
2806void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002807 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002808 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002809 Attr->set(Streamer->getRangesSectionSize());
2810 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002811}
2812
Frederic Riss63786b02015-03-15 20:45:43 +00002813/// \brief Insert the new line info sequence \p Seq into the current
2814/// set of already linked line info \p Rows.
2815static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2816 std::vector<DWARFDebugLine::Row> &Rows) {
2817 if (Seq.empty())
2818 return;
2819
2820 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2821 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2822 Seq.clear();
2823 return;
2824 }
2825
2826 auto InsertPoint = std::lower_bound(
2827 Rows.begin(), Rows.end(), Seq.front(),
2828 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2829 return LHS.Address < RHS.Address;
2830 });
2831
2832 // FIXME: this only removes the unneeded end_sequence if the
2833 // sequences have been inserted in order. using a global sort like
2834 // described in patchLineTableForUnit() and delaying the end_sequene
2835 // elimination to emitLineTableForUnit() we can get rid of all of them.
2836 if (InsertPoint != Rows.end() &&
2837 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2838 *InsertPoint = Seq.front();
2839 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2840 } else {
2841 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2842 }
2843
2844 Seq.clear();
2845}
2846
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002847static void patchStmtList(DIE &Die, DIEInteger Offset) {
2848 for (auto &V : Die.values())
2849 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002850 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002851 return;
2852 }
2853
2854 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2855}
2856
Frederic Riss63786b02015-03-15 20:45:43 +00002857/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2858/// recreate a relocated version of these for the address ranges that
2859/// are present in the binary.
2860void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2861 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002862 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002863 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2864 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2865 if (StmtList == -1ULL)
2866 return;
2867
2868 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002869 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2870 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002871
2872 // Parse the original line info for the unit.
2873 DWARFDebugLine::LineTable LineTable;
2874 uint32_t StmtOffset = StmtList;
2875 StringRef LineData = OrigDwarf.getLineSection().Data;
2876 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2877 Unit.getOrigUnit().getAddressByteSize());
2878 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2879 &StmtOffset);
2880
2881 // This vector is the output line table.
2882 std::vector<DWARFDebugLine::Row> NewRows;
2883 NewRows.reserve(LineTable.Rows.size());
2884
2885 // Current sequence of rows being extracted, before being inserted
2886 // in NewRows.
2887 std::vector<DWARFDebugLine::Row> Seq;
2888 const auto &FunctionRanges = Unit.getFunctionRanges();
2889 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2890
2891 // FIXME: This logic is meant to generate exactly the same output as
2892 // Darwin's classic dsynutil. There is a nicer way to implement this
2893 // by simply putting all the relocated line info in NewRows and simply
2894 // sorting NewRows before passing it to emitLineTableForUnit. This
2895 // should be correct as sequences for a function should stay
2896 // together in the sorted output. There are a few corner cases that
2897 // look suspicious though, and that required to implement the logic
2898 // this way. Revisit that once initial validation is finished.
2899
2900 // Iterate over the object file line info and extract the sequences
2901 // that correspond to linked functions.
2902 for (auto &Row : LineTable.Rows) {
2903 // Check wether we stepped out of the range. The range is
2904 // half-open, but consider accept the end address of the range if
2905 // it is marked as end_sequence in the input (because in that
2906 // case, the relocation offset is accurate and that entry won't
2907 // serve as the start of another function).
2908 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2909 Row.Address > CurrRange.stop() ||
2910 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2911 // We just stepped out of a known range. Insert a end_sequence
2912 // corresponding to the end of the range.
2913 uint64_t StopAddress = CurrRange != InvalidRange
2914 ? CurrRange.stop() + CurrRange.value()
2915 : -1ULL;
2916 CurrRange = FunctionRanges.find(Row.Address);
2917 bool CurrRangeValid =
2918 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2919 if (!CurrRangeValid) {
2920 CurrRange = InvalidRange;
2921 if (StopAddress != -1ULL) {
2922 // Try harder by looking in the DebugMapObject function
2923 // ranges map. There are corner cases where this finds a
2924 // valid entry. It's unclear if this is right or wrong, but
2925 // for now do as dsymutil.
2926 // FIXME: Understand exactly what cases this addresses and
2927 // potentially remove it along with the Ranges map.
2928 auto Range = Ranges.lower_bound(Row.Address);
2929 if (Range != Ranges.begin() && Range != Ranges.end())
2930 --Range;
2931
2932 if (Range != Ranges.end() && Range->first <= Row.Address &&
2933 Range->second.first >= Row.Address) {
2934 StopAddress = Row.Address + Range->second.second;
2935 }
2936 }
2937 }
2938 if (StopAddress != -1ULL && !Seq.empty()) {
2939 // Insert end sequence row with the computed end address, but
2940 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00002941 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00002942 NextLine.Address = StopAddress;
2943 NextLine.EndSequence = 1;
2944 NextLine.PrologueEnd = 0;
2945 NextLine.BasicBlock = 0;
2946 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00002947 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00002948 insertLineSequence(Seq, NewRows);
2949 }
2950
2951 if (!CurrRangeValid)
2952 continue;
2953 }
2954
2955 // Ignore empty sequences.
2956 if (Row.EndSequence && Seq.empty())
2957 continue;
2958
2959 // Relocate row address and add it to the current sequence.
2960 Row.Address += CurrRange.value();
2961 Seq.emplace_back(Row);
2962
2963 if (Row.EndSequence)
2964 insertLineSequence(Seq, NewRows);
2965 }
2966
2967 // Finished extracting, now emit the line tables.
2968 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2969 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2970 // prologue over and that works because we act as both producer and
2971 // consumer. It would be nicer to have a real configurable line
2972 // table emitter.
2973 if (LineTable.Prologue.Version != 2 ||
2974 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00002975 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00002976 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00002977 else {
2978 MCDwarfLineTableParams Params;
2979 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
2980 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
2981 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
2982 Streamer->emitLineTableForUnit(Params,
2983 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00002984 LineTable.Prologue.MinInstLength, NewRows,
2985 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00002986 }
Frederic Riss63786b02015-03-15 20:45:43 +00002987}
2988
Frederic Rissbce93ff2015-03-16 02:05:10 +00002989void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2990 Streamer->emitPubNamesForUnit(Unit);
2991 Streamer->emitPubTypesForUnit(Unit);
2992}
2993
Frederic Riss5a642072015-06-05 23:06:11 +00002994/// \brief Read the frame info stored in the object, and emit the
2995/// patched frame descriptions for the linked binary.
2996///
2997/// This is actually pretty easy as the data of the CIEs and FDEs can
2998/// be considered as black boxes and moved as is. The only thing to do
2999/// is to patch the addresses in the headers.
3000void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3001 DWARFContext &OrigDwarf,
3002 unsigned AddrSize) {
3003 StringRef FrameData = OrigDwarf.getDebugFrameSection();
3004 if (FrameData.empty())
3005 return;
3006
3007 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3008 uint32_t InputOffset = 0;
3009
3010 // Store the data of the CIEs defined in this object, keyed by their
3011 // offsets.
3012 DenseMap<uint32_t, StringRef> LocalCIES;
3013
3014 while (Data.isValidOffset(InputOffset)) {
3015 uint32_t EntryOffset = InputOffset;
3016 uint32_t InitialLength = Data.getU32(&InputOffset);
3017 if (InitialLength == 0xFFFFFFFF)
3018 return reportWarning("Dwarf64 bits no supported");
3019
3020 uint32_t CIEId = Data.getU32(&InputOffset);
3021 if (CIEId == 0xFFFFFFFF) {
3022 // This is a CIE, store it.
3023 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3024 LocalCIES[EntryOffset] = CIEData;
3025 // The -4 is to account for the CIEId we just read.
3026 InputOffset += InitialLength - 4;
3027 continue;
3028 }
3029
3030 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3031
3032 // Some compilers seem to emit frame info that doesn't start at
3033 // the function entry point, thus we can't just lookup the address
3034 // in the debug map. Use the linker's range map to see if the FDE
3035 // describes something that we can relocate.
3036 auto Range = Ranges.upper_bound(Loc);
3037 if (Range != Ranges.begin())
3038 --Range;
3039 if (Range == Ranges.end() || Range->first > Loc ||
3040 Range->second.first <= Loc) {
3041 // The +4 is to account for the size of the InitialLength field itself.
3042 InputOffset = EntryOffset + InitialLength + 4;
3043 continue;
3044 }
3045
3046 // This is an FDE, and we have a mapping.
3047 // Have we already emitted a corresponding CIE?
3048 StringRef CIEData = LocalCIES[CIEId];
3049 if (CIEData.empty())
3050 return reportWarning("Inconsistent debug_frame content. Dropping.");
3051
3052 // Look if we already emitted a CIE that corresponds to the
3053 // referenced one (the CIE data is the key of that lookup).
3054 auto IteratorInserted = EmittedCIEs.insert(
3055 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3056 // If there is no CIE yet for this ID, emit it.
3057 if (IteratorInserted.second ||
3058 // FIXME: dsymutil-classic only caches the last used CIE for
3059 // reuse. Mimic that behavior for now. Just removing that
3060 // second half of the condition and the LastCIEOffset variable
3061 // makes the code DTRT.
3062 LastCIEOffset != IteratorInserted.first->getValue()) {
3063 LastCIEOffset = Streamer->getFrameSectionSize();
3064 IteratorInserted.first->getValue() = LastCIEOffset;
3065 Streamer->emitCIE(CIEData);
3066 }
3067
3068 // Emit the FDE with updated address and CIE pointer.
3069 // (4 + AddrSize) is the size of the CIEId + initial_location
3070 // fields that will get reconstructed by emitFDE().
3071 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3072 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3073 Loc + Range->second.second,
3074 FrameData.substr(InputOffset, FDERemainingBytes));
3075 InputOffset += FDERemainingBytes;
3076 }
3077}
3078
Adrian Prantl3565af42015-09-14 16:46:10 +00003079void DwarfLinker::DIECloner::copyAbbrev(
3080 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
Frederic Riss29eedc72015-09-11 04:17:30 +00003081 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3082 dwarf::Form(Abbrev.hasChildren()));
3083
3084 for (const auto &Attr : Abbrev.attributes()) {
3085 uint16_t Form = Attr.Form;
3086 if (hasODR && isODRAttribute(Attr.Attr))
3087 Form = dwarf::DW_FORM_ref_addr;
3088 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3089 }
3090
Adrian Prantl3565af42015-09-14 16:46:10 +00003091 Linker.AssignAbbrev(Copy);
Frederic Riss29eedc72015-09-11 04:17:30 +00003092}
3093
Adrian Prantle5162db2015-09-22 22:20:50 +00003094bool DwarfLinker::registerModuleReference(
3095 const DWARFDebugInfoEntryMinimal &CUDie, const DWARFUnit &Unit,
3096 DebugMap &ModuleMap, unsigned Indent) {
3097 std::string PCMfile =
3098 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_GNU_dwo_name, "");
3099 if (PCMfile.empty())
3100 return false;
3101
3102 // Clang module DWARF skeleton CUs abuse this for the path to the module.
3103 std::string PCMpath =
3104 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_comp_dir, "");
3105
3106 if (Options.Verbose) {
3107 outs().indent(Indent);
3108 outs() << "Found clang module reference " << PCMfile;
3109 }
3110
3111 if (ClangModules.count(PCMfile)) {
3112 if (Options.Verbose)
3113 outs() << " [cached].\n";
3114 return true;
3115 }
3116 if (Options.Verbose)
3117 outs() << " ...\n";
3118
3119 // Cyclic dependencies are disallowed by Clang, but we still
3120 // shouldn't run into an infinite loop, so mark it as processed now.
3121 ClangModules.insert(PCMfile);
3122 loadClangModule(PCMfile, PCMpath, ModuleMap, Indent + 2);
3123 return true;
3124}
3125
Frederic Risseb85c8f2015-07-24 06:41:11 +00003126ErrorOr<const object::ObjectFile &>
3127DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3128 const DebugMap &Map) {
3129 auto ErrOrObjs =
3130 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
Frederic Rissafeac302015-08-31 05:16:35 +00003131 if (std::error_code EC = ErrOrObjs.getError()) {
Frederic Risseb85c8f2015-07-24 06:41:11 +00003132 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
Frederic Rissafeac302015-08-31 05:16:35 +00003133 return EC;
3134 }
Frederic Risseb85c8f2015-07-24 06:41:11 +00003135 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3136 if (std::error_code EC = ErrOrObj.getError())
3137 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3138 return ErrOrObj;
3139}
3140
Adrian Prantle5162db2015-09-22 22:20:50 +00003141void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
3142 DebugMap &ModuleMap, unsigned Indent) {
3143 SmallString<80> Path(Options.PrependPath);
3144 if (sys::path::is_relative(Filename))
3145 sys::path::append(Path, ModulePath, Filename);
3146 else
3147 sys::path::append(Path, Filename);
3148 BinaryHolder ObjHolder(Options.Verbose);
3149 auto &Obj =
3150 ModuleMap.addDebugMapObject(Path, sys::TimeValue::PosixZeroTime());
3151 auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
3152 if (!ErrOrObj) {
3153 ClangModules.erase(ClangModules.find(Filename));
3154 return;
3155 }
3156
3157 // FIXME: At this point dsymutil should verify the DW_AT_gnu_dwo_id
3158 // against the module hash of the clang module.
3159
Benjamin Kramer008f4be2015-09-23 10:38:59 +00003160 std::unique_ptr<CompileUnit> Unit;
Adrian Prantle5162db2015-09-22 22:20:50 +00003161
3162 // Setup access to the debug info.
3163 DWARFContextInMemory DwarfContext(*ErrOrObj);
3164 RelocationManager RelocMgr(*this);
3165 for (const auto &CU : DwarfContext.compile_units()) {
3166 auto *CUDie = CU->getUnitDIE(false);
3167 // Recursively get all modules imported by this one.
3168 if (!registerModuleReference(*CUDie, *CU, ModuleMap, Indent)) {
3169 // Add this module.
3170 if (Unit) {
3171 errs() << Filename << ": Clang modules are expected to have exactly"
3172 << " 1 compile unit.\n";
3173 exitDsymutil(1);
3174 }
Benjamin Kramer008f4be2015-09-23 10:38:59 +00003175 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR);
Adrian Prantle5162db2015-09-22 22:20:50 +00003176 Unit->setHasInterestingContent();
3177 gatherDIEParents(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3178 ODRContexts);
3179 // Keep everything.
3180 Unit->markEverythingAsKept();
3181 }
3182 }
3183 if (Options.Verbose) {
3184 outs().indent(Indent);
3185 outs() << "cloning .debug_info from " << Filename << "\n";
3186 }
3187
3188 DIECloner(*this, RelocMgr, DIEAlloc, MutableArrayRef<CompileUnit>(*Unit),
3189 Options)
3190 .cloneAllCompileUnits(DwarfContext);
3191}
3192
Adrian Prantl3565af42015-09-14 16:46:10 +00003193void DwarfLinker::DIECloner::cloneAllCompileUnits(
3194 DWARFContextInMemory &DwarfContext) {
3195 if (!Linker.Streamer)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003196 return;
3197
3198 for (auto &CurrentUnit : CompileUnits) {
3199 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Adrian Prantl3565af42015-09-14 16:46:10 +00003200 CurrentUnit.setStartOffset(Linker.OutputDebugInfoSize);
Adrian Prantl3abe18d2015-09-14 23:27:26 +00003201 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PC offset */,
3202 11 /* Unit Header size */, 0);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003203 CurrentUnit.setOutputUnitDIE(OutputDIE);
Adrian Prantl3565af42015-09-14 16:46:10 +00003204 Linker.OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3205 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003206 continue;
3207 // FIXME: for compatibility with the classic dsymutil, we emit
3208 // an empty line table for the unit, even if the unit doesn't
3209 // actually exist in the DIE tree.
Adrian Prantl3565af42015-09-14 16:46:10 +00003210 Linker.patchLineTableForUnit(CurrentUnit, DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003211 if (!OutputDIE)
3212 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003213 Linker.patchRangesForUnit(CurrentUnit, DwarfContext);
3214 Linker.Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3215 Linker.emitAcceleratorEntriesForUnit(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003216 }
3217
Adrian Prantl3565af42015-09-14 16:46:10 +00003218 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003219 return;
3220
3221 // Emit all the compile unit's debug information.
3222 for (auto &CurrentUnit : CompileUnits) {
Adrian Prantl3565af42015-09-14 16:46:10 +00003223 Linker.generateUnitRanges(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003224 CurrentUnit.fixupForwardReferences();
Adrian Prantl3565af42015-09-14 16:46:10 +00003225 Linker.Streamer->emitCompileUnitHeader(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003226 if (!CurrentUnit.getOutputUnitDIE())
3227 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003228 Linker.Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003229 }
3230}
3231
Frederic Rissd3455182015-01-28 18:27:01 +00003232bool DwarfLinker::link(const DebugMap &Map) {
3233
Frederic Rissc99ea202015-02-28 00:29:11 +00003234 if (!createStreamer(Map.getTriple(), OutputFilename))
3235 return false;
3236
Frederic Rissb8b43d52015-03-04 22:07:44 +00003237 // Size of the DIEs (and headers) generated for the linked output.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003238 OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003239 // A unique ID that identifies each compile unit.
Adrian Prantle5162db2015-09-22 22:20:50 +00003240 UnitID = 0;
3241 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3242
Frederic Rissd3455182015-01-28 18:27:01 +00003243 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003244 CurrentDebugObject = Obj.get();
3245
Frederic Rissb9818322015-02-28 00:29:07 +00003246 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003247 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003248 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3249 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003250 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003251
Frederic Riss1036e642015-02-13 23:18:22 +00003252 // Look for relocations that correspond to debug map entries.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003253 RelocationManager RelocMgr(*this);
3254 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003255 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003256 outs() << "No valid relocations found. Skipping.\n";
3257 continue;
3258 }
3259
Frederic Riss563cba62015-01-28 22:15:14 +00003260 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003261 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003262 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003263
Frederic Riss563cba62015-01-28 22:15:14 +00003264 // In a first phase, just read in the debug info and store the DIE
3265 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00003266 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003267 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003268 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003269 outs() << "Input compilation unit:";
3270 CUDie->dump(outs(), CU.get(), 0);
3271 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003272 if (!registerModuleReference(*CUDie, *CU, ModuleMap)) {
3273 Units.emplace_back(*CU, UnitID++, !Options.NoODR);
3274 gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
3275 StringPool, ODRContexts);
3276 }
Frederic Rissd3455182015-01-28 18:27:01 +00003277 }
Frederic Riss563cba62015-01-28 22:15:14 +00003278
Frederic Riss84c09a52015-02-13 23:18:34 +00003279 // Then mark all the DIEs that need to be present in the linked
3280 // output and collect some information about them. Note that this
3281 // loop can not be merged with the previous one becaue cross-cu
3282 // references require the ParentIdx to be setup for every CU in
3283 // the object file before calling this.
3284 for (auto &CurrentUnit : Units)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003285 lookForDIEsToKeep(RelocMgr, *CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00003286 CurrentUnit, 0);
3287
Frederic Riss23e20e92015-03-07 01:25:09 +00003288 // The calls to applyValidRelocs inside cloneDIE will walk the
3289 // reloc array again (in the same way findValidRelocsInDebugInfo()
3290 // did). We need to reset the NextValidReloc index to the beginning.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003291 RelocMgr.resetValidRelocs();
3292 if (RelocMgr.hasValidRelocs())
Adrian Prantl3565af42015-09-14 16:46:10 +00003293 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3294 .cloneAllCompileUnits(DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003295 if (!Options.NoOutput && !Units.empty())
Frederic Riss5a642072015-06-05 23:06:11 +00003296 patchFrameInfoForObject(*Obj, DwarfContext,
3297 Units[0].getOrigUnit().getAddressByteSize());
3298
Frederic Riss563cba62015-01-28 22:15:14 +00003299 // Clean-up before starting working on the next object.
3300 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003301 }
3302
Frederic Rissb8b43d52015-03-04 22:07:44 +00003303 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003304 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003305 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003306 Streamer->emitStrings(StringPool);
3307 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003308
Frederic Riss24faade2015-09-02 16:49:13 +00003309 return Options.NoOutput ? true : Streamer->finish(Map);
Frederic Riss231f7142014-12-12 17:31:24 +00003310}
3311}
Frederic Rissd3455182015-01-28 18:27:01 +00003312
Frederic Riss30711fb2015-08-26 05:09:52 +00003313/// \brief Get the offset of string \p S in the string table. This
3314/// can insert a new element or return the offset of a preexisitng
3315/// one.
3316uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3317 if (S.empty() && !Strings.empty())
3318 return 0;
3319
3320 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3321 MapTy::iterator It;
3322 bool Inserted;
3323
3324 // A non-empty string can't be at offset 0, so if we have an entry
3325 // with a 0 offset, it must be a previously interned string.
3326 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3327 if (Inserted || It->getValue().first == 0) {
3328 // Set offset and chain at the end of the entries list.
3329 It->getValue().first = CurrentEndOffset;
3330 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3331 Last->getValue().second = &*It;
3332 Last = &*It;
3333 }
3334 return It->getValue().first;
3335}
3336
3337/// \brief Put \p S into the StringMap so that it gets permanent
3338/// storage, but do not actually link it in the chain of elements
3339/// that go into the output section. A latter call to
3340/// getStringOffset() with the same string will chain it though.
3341StringRef NonRelocatableStringpool::internString(StringRef S) {
3342 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3343 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3344 return InsertResult.first->getKey();
3345}
3346
Frederic Riss65e145c2015-08-26 05:09:55 +00003347void warn(const Twine &Warning, const Twine &Context) {
3348 errs() << Twine("while processing ") + Context + ":\n";
3349 errs() << Twine("warning: ") + Warning + "\n";
3350}
3351
3352bool error(const Twine &Error, const Twine &Context) {
3353 errs() << Twine("while processing ") + Context + ":\n";
3354 errs() << Twine("error: ") + Error + "\n";
3355 return false;
3356}
3357
Frederic Rissb9818322015-02-28 00:29:07 +00003358bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3359 const LinkOptions &Options) {
3360 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003361 return Linker.link(DM);
3362}
3363}
Frederic Riss231f7142014-12-12 17:31:24 +00003364}