blob: 6574a479792a1b78e807186125776697f9121977 [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"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000016#include "llvm/ADT/StringMap.h"
17#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
Frederic Riss9d441b62015-03-06 23:22:50 +0000251 /// \brief Compute the end offset for this unit. Must be
252 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000253 /// \returns the next unit offset (which is also the current
254 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000255 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000256
Frederic Riss6afcfce2015-03-13 18:35:57 +0000257 /// \brief Keep track of a forward reference to DIE \p Die in \p
258 /// RefUnit by \p Attr. The attribute should be fixed up later to
Frederic Riss1c650942015-07-21 22:41:43 +0000259 /// point to the absolute offset of \p Die in the debug_info section
260 /// or to the canonical offset of \p Ctxt if it is non-null.
Frederic Riss6afcfce2015-03-13 18:35:57 +0000261 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000262 DeclContext *Ctxt, PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000263
264 /// \brief Apply all fixups recored by noteForwardReference().
265 void fixupForwardReferences();
266
Frederic Riss1af75f72015-03-12 18:45:10 +0000267 /// \brief Add a function range [\p LowPC, \p HighPC) that is
268 /// relocatad by applying offset \p PCOffset.
269 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
270
Frederic Riss5c9c7062015-03-13 23:55:29 +0000271 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000272 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000273 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000274
Frederic Rissdfb97902015-03-14 15:49:07 +0000275 /// \brief Keep track of a location attribute pointing to a location
276 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000277 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000278
Frederic Rissbce93ff2015-03-16 02:05:10 +0000279 /// \brief Add a name accelerator entry for \p Die with \p Name
280 /// which is stored in the string table at \p Offset.
281 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
282 bool SkipPubnamesSection = false);
283
284 /// \brief Add a type accelerator entry for \p Die with \p Name
285 /// which is stored in the string table at \p Offset.
286 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
287
288 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000289 StringRef Name; ///< Name of the entry.
290 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000291 uint32_t NameOffset; ///< Offset of Name in the string pool.
292 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
293
294 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
295 bool SkipPubSection = false)
296 : Name(Name), Die(Die), NameOffset(NameOffset),
297 SkipPubSection(SkipPubSection) {}
298 };
299
300 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
301 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
302
Frederic Riss1c650942015-07-21 22:41:43 +0000303 /// Get the full path for file \a FileNum in the line table
304 const char *getResolvedPath(unsigned FileNum) {
305 if (FileNum >= ResolvedPaths.size())
306 return nullptr;
307 return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
308 : nullptr;
309 }
310
311 /// Set the fully resolved path for the line-table's file \a FileNum
312 /// to \a Path.
313 void setResolvedPath(unsigned FileNum, const std::string &Path) {
314 if (ResolvedPaths.size() <= FileNum)
315 ResolvedPaths.resize(FileNum + 1);
316 ResolvedPaths[FileNum] = Path;
317 }
318
Frederic Riss563cba62015-01-28 22:15:14 +0000319private:
320 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000321 unsigned ID;
Frederic Riss1c650942015-07-21 22:41:43 +0000322 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
323 DIE *CUDie; ///< Root of the linked DIE tree.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000324
325 uint64_t StartOffset;
326 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000327
Frederic Riss5a62dc32015-03-13 18:35:54 +0000328 uint64_t LowPc;
329 uint64_t HighPc;
330
Frederic Riss9833de62015-03-06 23:22:53 +0000331 /// \brief A list of attributes to fixup with the absolute offset of
332 /// a DIE in the debug_info section.
333 ///
334 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000335 /// cloning because for cross-cu forward refences the target DIE's
336 /// offset isn't known you emit the reference attribute.
Frederic Riss1c650942015-07-21 22:41:43 +0000337 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
338 PatchLocation>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000339
Frederic Riss25440872015-03-13 23:30:31 +0000340 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000341 /// \brief The ranges in that interval map are the PC ranges for
342 /// functions in this unit, associated with the PC offset to apply
343 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000344 FunctionIntervals Ranges;
345
346 /// \brief DW_AT_ranges attributes to patch after we have gathered
347 /// all the unit's function addresses.
348 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000349 std::vector<PatchLocation> RangeAttributes;
350 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000351 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000352
353 /// \brief Location attributes that need to be transfered from th
354 /// original debug_loc section to the liked one. They are stored
355 /// along with the PC offset that is to be applied to their
356 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000357 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000358
359 /// \brief Accelerator entries for the unit, both for the pub*
360 /// sections and the apple* ones.
361 /// @{
362 std::vector<AccelInfo> Pubnames;
363 std::vector<AccelInfo> Pubtypes;
364 /// @}
Frederic Riss1c650942015-07-21 22:41:43 +0000365
366 /// Cached resolved paths from the line table.
367 std::vector<std::string> ResolvedPaths;
368
369 /// Is this unit subject to the ODR rule?
370 bool HasODR;
Frederic Riss563cba62015-01-28 22:15:14 +0000371};
372
Frederic Riss9d441b62015-03-06 23:22:50 +0000373uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000374 NextUnitOffset = StartOffset + 11 /* Header size */;
375 // The root DIE might be null, meaning that the Unit had nothing to
376 // contribute to the linked output. In that case, we will emit the
377 // unit header without any actual DIE.
378 if (CUDie)
379 NextUnitOffset += CUDie->getSize();
380 return NextUnitOffset;
381}
382
Frederic Riss6afcfce2015-03-13 18:35:57 +0000383/// \brief Keep track of a forward cross-cu reference from this unit
384/// to \p Die that lives in \p RefUnit.
385void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000386 DeclContext *Ctxt, PatchLocation Attr) {
387 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000388}
389
390/// \brief Apply all fixups recorded by noteForwardReference().
391void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000392 for (const auto &Ref : ForwardDIEReferences) {
393 DIE *RefDie;
394 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000395 PatchLocation Attr;
Frederic Riss1c650942015-07-21 22:41:43 +0000396 DeclContext *Ctxt;
397 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
398 if (Ctxt && Ctxt->getCanonicalDIEOffset())
399 Attr.set(Ctxt->getCanonicalDIEOffset());
400 else
401 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000402 }
Frederic Riss9833de62015-03-06 23:22:53 +0000403}
404
Frederic Riss5a62dc32015-03-13 18:35:54 +0000405void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
406 int64_t PcOffset) {
407 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
408 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
409 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000410}
411
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000412void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000413 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
414 RangeAttributes.push_back(Attr);
415 else
416 UnitRangeAttribute = Attr;
417}
418
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000419void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000420 LocationAttributes.emplace_back(Attr, PcOffset);
421}
422
Frederic Rissbce93ff2015-03-16 02:05:10 +0000423/// \brief Add a name accelerator entry for \p Die with \p Name
424/// which is stored in the string table at \p Offset.
425void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
426 uint32_t Offset, bool SkipPubSection) {
427 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
428}
429
430/// \brief Add a type accelerator entry for \p Die with \p Name
431/// which is stored in the string table at \p Offset.
432void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
433 uint32_t Offset) {
434 Pubtypes.emplace_back(Name, Die, Offset, false);
435}
436
Frederic Rissc99ea202015-02-28 00:29:11 +0000437/// \brief The Dwarf streaming logic
438///
439/// All interactions with the MC layer that is used to build the debug
440/// information binary representation are handled in this class.
441class DwarfStreamer {
442 /// \defgroup MCObjects MC layer objects constructed by the streamer
443 /// @{
444 std::unique_ptr<MCRegisterInfo> MRI;
445 std::unique_ptr<MCAsmInfo> MAI;
446 std::unique_ptr<MCObjectFileInfo> MOFI;
447 std::unique_ptr<MCContext> MC;
448 MCAsmBackend *MAB; // Owned by MCStreamer
449 std::unique_ptr<MCInstrInfo> MII;
450 std::unique_ptr<MCSubtargetInfo> MSTI;
451 MCCodeEmitter *MCE; // Owned by MCStreamer
452 MCStreamer *MS; // Owned by AsmPrinter
453 std::unique_ptr<TargetMachine> TM;
454 std::unique_ptr<AsmPrinter> Asm;
455 /// @}
456
457 /// \brief the file we stream the linked Dwarf to.
458 std::unique_ptr<raw_fd_ostream> OutFile;
459
Frederic Riss25440872015-03-13 23:30:31 +0000460 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000461 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000462 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000463 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000464
Frederic Rissbce93ff2015-03-16 02:05:10 +0000465 /// \brief Emit the pubnames or pubtypes section contribution for \p
466 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000467 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000468 const CompileUnit &Unit,
469 const std::vector<CompileUnit::AccelInfo> &Names);
470
Frederic Rissc99ea202015-02-28 00:29:11 +0000471public:
472 /// \brief Actually create the streamer and the ouptut file.
473 ///
474 /// This could be done directly in the constructor, but it feels
475 /// more natural to handle errors through return value.
476 bool init(Triple TheTriple, StringRef OutputFilename);
477
Frederic Rissb8b43d52015-03-04 22:07:44 +0000478 /// \brief Dump the file to the disk.
Frederic Riss24faade2015-09-02 16:49:13 +0000479 bool finish(const DebugMap &);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000480
481 AsmPrinter &getAsmPrinter() const { return *Asm; }
482
483 /// \brief Set the current output section to debug_info and change
484 /// the MC Dwarf version to \p DwarfVersion.
485 void switchToDebugInfoSection(unsigned DwarfVersion);
486
487 /// \brief Emit the compilation unit header for \p Unit in the
488 /// debug_info section.
489 ///
490 /// As a side effect, this also switches the current Dwarf version
491 /// of the MC layer to the one of U.getOrigUnit().
492 void emitCompileUnitHeader(CompileUnit &Unit);
493
494 /// \brief Recursively emit the DIE tree rooted at \p Die.
495 void emitDIE(DIE &Die);
496
497 /// \brief Emit the abbreviation table \p Abbrevs to the
498 /// debug_abbrev section.
499 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000500
501 /// \brief Emit the string table described by \p Pool.
502 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000503
504 /// \brief Emit debug_ranges for \p FuncRange by translating the
505 /// original \p Entries.
506 void emitRangesEntries(
507 int64_t UnitPcOffset, uint64_t OrigLowPc,
508 FunctionIntervals::const_iterator FuncRange,
509 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
510 unsigned AddressSize);
511
Frederic Riss563b1b02015-03-14 03:46:51 +0000512 /// \brief Emit debug_aranges entries for \p Unit and if \p
513 /// DoRangesSection is true, also emit the debug_ranges entries for
514 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
515 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000516
517 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000518
519 /// \brief Emit the debug_loc contribution for \p Unit by copying
520 /// the entries from \p Dwarf and offseting them. Update the
521 /// location attributes to point to the new entries.
522 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000523
524 /// \brief Emit the line table described in \p Rows into the
525 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000526 void emitLineTableForUnit(MCDwarfLineTableParams Params,
527 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000528 std::vector<DWARFDebugLine::Row> &Rows,
529 unsigned AdddressSize);
530
531 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000532
533 /// \brief Emit the .debug_pubnames contribution for \p Unit.
534 void emitPubNamesForUnit(const CompileUnit &Unit);
535
536 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
537 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000538
539 /// \brief Emit a CIE.
540 void emitCIE(StringRef CIEBytes);
541
542 /// \brief Emit an FDE with data \p Bytes.
543 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
544 StringRef Bytes);
545
546 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000547};
548
549bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
550 std::string ErrorStr;
551 std::string TripleName;
552 StringRef Context = "dwarf streamer init";
553
554 // Get the target.
555 const Target *TheTarget =
556 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
557 if (!TheTarget)
558 return error(ErrorStr, Context);
559 TripleName = TheTriple.getTriple();
560
561 // Create all the MC Objects.
562 MRI.reset(TheTarget->createMCRegInfo(TripleName));
563 if (!MRI)
564 return error(Twine("no register info for target ") + TripleName, Context);
565
566 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
567 if (!MAI)
568 return error("no asm info for target " + TripleName, Context);
569
570 MOFI.reset(new MCObjectFileInfo);
571 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000572 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
Frederic Rissc99ea202015-02-28 00:29:11 +0000573 *MC);
574
575 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
576 if (!MAB)
577 return error("no asm backend for target " + TripleName, Context);
578
579 MII.reset(TheTarget->createMCInstrInfo());
580 if (!MII)
581 return error("no instr info info for target " + TripleName, Context);
582
583 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
584 if (!MSTI)
585 return error("no subtarget info for target " + TripleName, Context);
586
Eric Christopher0169e422015-03-10 22:03:14 +0000587 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000588 if (!MCE)
589 return error("no code emitter for target " + TripleName, Context);
590
591 // Create the output file.
592 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000593 OutFile =
594 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000595 if (EC)
596 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
597
Rafael Espindolaf696df12015-03-16 22:29:29 +0000598 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000599 *MSTI, false,
600 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000601 if (!MS)
602 return error("no object streamer for target " + TripleName, Context);
603
604 // Finally create the AsmPrinter we'll use to emit the DIEs.
605 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
606 if (!TM)
607 return error("no target machine for target " + TripleName, Context);
608
609 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
610 if (!Asm)
611 return error("no asm printer for target " + TripleName, Context);
612
Frederic Riss25440872015-03-13 23:30:31 +0000613 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000614 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000615 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000616 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000617
Frederic Rissc99ea202015-02-28 00:29:11 +0000618 return true;
619}
620
Frederic Riss24faade2015-09-02 16:49:13 +0000621bool DwarfStreamer::finish(const DebugMap &DM) {
622 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
623 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
624
Frederic Rissc99ea202015-02-28 00:29:11 +0000625 MS->Finish();
626 return true;
627}
628
Frederic Rissb8b43d52015-03-04 22:07:44 +0000629/// \brief Set the current output section to debug_info and change
630/// the MC Dwarf version to \p DwarfVersion.
631void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
632 MS->SwitchSection(MOFI->getDwarfInfoSection());
633 MC->setDwarfVersion(DwarfVersion);
634}
635
636/// \brief Emit the compilation unit header for \p Unit in the
637/// debug_info section.
638///
639/// A Dwarf scetion header is encoded as:
640/// uint32_t Unit length (omiting this field)
641/// uint16_t Version
642/// uint32_t Abbreviation table offset
643/// uint8_t Address size
644///
645/// Leading to a total of 11 bytes.
646void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
647 unsigned Version = Unit.getOrigUnit().getVersion();
648 switchToDebugInfoSection(Version);
649
650 // Emit size of content not including length itself. The size has
651 // already been computed in CompileUnit::computeOffsets(). Substract
652 // 4 to that size to account for the length field.
653 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
654 Asm->EmitInt16(Version);
655 // We share one abbreviations table across all units so it's always at the
656 // start of the section.
657 Asm->EmitInt32(0);
658 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
659}
660
661/// \brief Emit the \p Abbrevs array as the shared abbreviation table
662/// for the linked Dwarf file.
663void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
664 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
665 Asm->emitDwarfAbbrevs(Abbrevs);
666}
667
668/// \brief Recursively emit the DIE tree rooted at \p Die.
669void DwarfStreamer::emitDIE(DIE &Die) {
670 MS->SwitchSection(MOFI->getDwarfInfoSection());
671 Asm->emitDwarfDIE(Die);
672}
673
Frederic Rissef648462015-03-06 17:56:30 +0000674/// \brief Emit the debug_str section stored in \p Pool.
675void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000676 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000677 for (auto *Entry = Pool.getFirstEntry(); Entry;
678 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000679 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000680 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
681}
682
Frederic Riss25440872015-03-13 23:30:31 +0000683/// \brief Emit the debug_range section contents for \p FuncRange by
684/// translating the original \p Entries. The debug_range section
685/// format is totally trivial, consisting just of pairs of address
686/// sized addresses describing the ranges.
687void DwarfStreamer::emitRangesEntries(
688 int64_t UnitPcOffset, uint64_t OrigLowPc,
689 FunctionIntervals::const_iterator FuncRange,
690 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
691 unsigned AddressSize) {
692 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
693
694 // Offset each range by the right amount.
Frederic Riss94546202015-08-31 05:09:32 +0000695 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
Frederic Riss25440872015-03-13 23:30:31 +0000696 for (const auto &Range : Entries) {
697 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
698 warn("unsupported base address selection operation",
699 "emitting debug_ranges");
700 break;
701 }
702 // Do not emit empty ranges.
703 if (Range.StartAddress == Range.EndAddress)
704 continue;
705
706 // All range entries should lie in the function range.
707 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
708 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
709 warn("inconsistent range data.", "emitting debug_ranges");
710 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
711 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
712 RangesSectionSize += 2 * AddressSize;
713 }
714
715 // Add the terminator entry.
716 MS->EmitIntValue(0, AddressSize);
717 MS->EmitIntValue(0, AddressSize);
718 RangesSectionSize += 2 * AddressSize;
719}
720
Frederic Riss563b1b02015-03-14 03:46:51 +0000721/// \brief Emit the debug_aranges contribution of a unit and
722/// if \p DoDebugRanges is true the debug_range contents for a
723/// compile_unit level DW_AT_ranges attribute (Which are basically the
724/// same thing with a different base address).
725/// Just aggregate all the ranges gathered inside that unit.
726void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
727 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000728 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
729 // Gather the ranges in a vector, so that we can simplify them. The
730 // IntervalMap will have coalesced the non-linked ranges, but here
731 // we want to coalesce the linked addresses.
732 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
733 const auto &FunctionRanges = Unit.getFunctionRanges();
734 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
735 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000736 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
737 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000738
739 // The object addresses where sorted, but again, the linked
740 // addresses might end up in a different order.
741 std::sort(Ranges.begin(), Ranges.end());
742
Frederic Riss563b1b02015-03-14 03:46:51 +0000743 if (!Ranges.empty()) {
744 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
745
Rafael Espindola9ab09232015-03-17 20:07:06 +0000746 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
747 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000748
749 unsigned HeaderSize =
750 sizeof(int32_t) + // Size of contents (w/o this field
751 sizeof(int16_t) + // DWARF ARange version number
752 sizeof(int32_t) + // Offset of CU in the .debug_info section
753 sizeof(int8_t) + // Pointer Size (in bytes)
754 sizeof(int8_t); // Segment Size (in bytes)
755
756 unsigned TupleSize = AddressSize * 2;
757 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
758
759 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000760 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000761 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
762 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
763 Asm->EmitInt8(AddressSize); // Address size
764 Asm->EmitInt8(0); // Segment size
765
Lang Hames9ff69c82015-04-24 19:11:51 +0000766 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000767
768 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
769 ++Range) {
770 uint64_t RangeStart = Range->first;
771 MS->EmitIntValue(RangeStart, AddressSize);
772 while ((Range + 1) != End && Range->second == (Range + 1)->first)
773 ++Range;
774 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
775 }
776
777 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000778 Asm->OutStreamer->EmitIntValue(0, AddressSize);
779 Asm->OutStreamer->EmitIntValue(0, AddressSize);
780 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000781 }
782
783 if (!DoDebugRanges)
784 return;
785
786 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
787 // Offset each range by the right amount.
788 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000789 // Emit coalesced ranges.
790 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000791 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000792 while (Range + 1 != End && Range->second == (Range + 1)->first)
793 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000794 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000795 RangesSectionSize += 2 * AddressSize;
796 }
797
798 // Add the terminator entry.
799 MS->EmitIntValue(0, AddressSize);
800 MS->EmitIntValue(0, AddressSize);
801 RangesSectionSize += 2 * AddressSize;
802}
803
Frederic Rissdfb97902015-03-14 15:49:07 +0000804/// \brief Emit location lists for \p Unit and update attribtues to
805/// point to the new entries.
806void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
807 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000808 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000809
810 if (Attributes.empty())
811 return;
812
813 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
814
815 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
816 const DWARFSection &InputSec = Dwarf.getLocSection();
817 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
818 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000819 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000820 int64_t UnitPcOffset = 0;
821 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
822 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
823 if (OrigLowPc != -1ULL)
824 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
825
826 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000827 uint32_t Offset = Attr.first.get();
828 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000829 // This is the quantity to add to the old location address to get
830 // the correct address for the new one.
831 int64_t LocPcOffset = Attr.second + UnitPcOffset;
832 while (Data.isValidOffset(Offset)) {
833 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
834 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
835 LocSectionSize += 2 * AddressSize;
836 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000837 Asm->OutStreamer->EmitIntValue(0, AddressSize);
838 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000839 break;
840 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000841 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
842 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000843 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000844 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000845 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000846 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000847 StringRef(InputSec.Data.substr(Offset, Length)));
848 Offset += Length;
849 LocSectionSize += Length + 2;
850 }
851 }
852}
853
Frederic Rissa5e14532015-08-07 15:14:13 +0000854void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
855 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000856 unsigned MinInstLength,
857 std::vector<DWARFDebugLine::Row> &Rows,
858 unsigned PointerSize) {
859 // Switch to the section where the table will be emitted into.
860 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000861 MCSymbol *LineStartSym = MC->createTempSymbol();
862 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000863
864 // The first 4 bytes is the total length of the information for this
865 // compilation unit (not including these 4 bytes for the length).
866 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000867 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000868 // Copy Prologue.
869 MS->EmitBytes(PrologueBytes);
870 LineSectionSize += PrologueBytes.size() + 4;
871
Frederic Rissc3820d02015-03-15 22:20:28 +0000872 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000873 raw_svector_ostream EncodingOS(EncodingBuffer);
874
875 if (Rows.empty()) {
876 // We only have the dummy entry, dsymutil emits an entry with a 0
877 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000878 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000879 MS->EmitBytes(EncodingOS.str());
880 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000881 MS->EmitLabel(LineEndSym);
882 return;
883 }
884
885 // Line table state machine fields
886 unsigned FileNum = 1;
887 unsigned LastLine = 1;
888 unsigned Column = 0;
889 unsigned IsStatement = 1;
890 unsigned Isa = 0;
891 uint64_t Address = -1ULL;
892
893 unsigned RowsSinceLastSequence = 0;
894
895 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
896 auto &Row = Rows[Idx];
897
898 int64_t AddressDelta;
899 if (Address == -1ULL) {
900 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
901 MS->EmitULEB128IntValue(PointerSize + 1);
902 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
903 MS->EmitIntValue(Row.Address, PointerSize);
904 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
905 AddressDelta = 0;
906 } else {
907 AddressDelta = (Row.Address - Address) / MinInstLength;
908 }
909
910 // FIXME: code copied and transfromed from
911 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
912 // this code, but the current compatibility requirement with
913 // classic dsymutil makes it hard. Revisit that once this
914 // requirement is dropped.
915
916 if (FileNum != Row.File) {
917 FileNum = Row.File;
918 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
919 MS->EmitULEB128IntValue(FileNum);
920 LineSectionSize += 1 + getULEB128Size(FileNum);
921 }
922 if (Column != Row.Column) {
923 Column = Row.Column;
924 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
925 MS->EmitULEB128IntValue(Column);
926 LineSectionSize += 1 + getULEB128Size(Column);
927 }
928
929 // FIXME: We should handle the discriminator here, but dsymutil
930 // doesn' consider it, thus ignore it for now.
931
932 if (Isa != Row.Isa) {
933 Isa = Row.Isa;
934 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
935 MS->EmitULEB128IntValue(Isa);
936 LineSectionSize += 1 + getULEB128Size(Isa);
937 }
938 if (IsStatement != Row.IsStmt) {
939 IsStatement = Row.IsStmt;
940 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
941 LineSectionSize += 1;
942 }
943 if (Row.BasicBlock) {
944 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
945 LineSectionSize += 1;
946 }
947
948 if (Row.PrologueEnd) {
949 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
950 LineSectionSize += 1;
951 }
952
953 if (Row.EpilogueBegin) {
954 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
955 LineSectionSize += 1;
956 }
957
958 int64_t LineDelta = int64_t(Row.Line) - LastLine;
959 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000960 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000961 MS->EmitBytes(EncodingOS.str());
962 LineSectionSize += EncodingBuffer.size();
963 EncodingBuffer.resize(0);
964 Address = Row.Address;
965 LastLine = Row.Line;
966 RowsSinceLastSequence++;
967 } else {
968 if (LineDelta) {
969 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
970 MS->EmitSLEB128IntValue(LineDelta);
971 LineSectionSize += 1 + getSLEB128Size(LineDelta);
972 }
973 if (AddressDelta) {
974 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
975 MS->EmitULEB128IntValue(AddressDelta);
976 LineSectionSize += 1 + getULEB128Size(AddressDelta);
977 }
Frederic Rissa5e14532015-08-07 15:14:13 +0000978 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000979 MS->EmitBytes(EncodingOS.str());
980 LineSectionSize += EncodingBuffer.size();
981 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +0000982 Address = -1ULL;
983 LastLine = FileNum = IsStatement = 1;
984 RowsSinceLastSequence = Column = Isa = 0;
985 }
986 }
987
988 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000989 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000990 MS->EmitBytes(EncodingOS.str());
991 LineSectionSize += EncodingBuffer.size();
992 EncodingBuffer.resize(0);
993 }
994
995 MS->EmitLabel(LineEndSym);
996}
997
Frederic Rissbce93ff2015-03-16 02:05:10 +0000998/// \brief Emit the pubnames or pubtypes section contribution for \p
999/// Unit into \p Sec. The data is provided in \p Names.
1000void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001001 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001002 const std::vector<CompileUnit::AccelInfo> &Names) {
1003 if (Names.empty())
1004 return;
1005
1006 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001007 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001008 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1009 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001010
1011 bool HeaderEmitted = false;
1012 // Emit the pubnames for this compilation unit.
1013 for (const auto &Name : Names) {
1014 if (Name.SkipPubSection)
1015 continue;
1016
1017 if (!HeaderEmitted) {
1018 // Emit the header.
1019 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001020 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001021 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001022 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001023 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1024 HeaderEmitted = true;
1025 }
1026 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001027 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001028 StringRef(Name.Name.data(), Name.Name.size() + 1));
1029 }
1030
1031 if (!HeaderEmitted)
1032 return;
1033 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001034 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001035}
1036
1037/// \brief Emit .debug_pubnames for \p Unit.
1038void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1039 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1040 "names", Unit, Unit.getPubnames());
1041}
1042
1043/// \brief Emit .debug_pubtypes for \p Unit.
1044void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1045 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1046 "types", Unit, Unit.getPubtypes());
1047}
1048
Frederic Riss5a642072015-06-05 23:06:11 +00001049/// \brief Emit a CIE into the debug_frame section.
1050void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1051 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1052
1053 MS->EmitBytes(CIEBytes);
1054 FrameSectionSize += CIEBytes.size();
1055}
1056
1057/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1058/// contains the FDE data without the length, CIE offset and address
1059/// which will be replaced with the paramter values.
1060void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1061 uint32_t Address, StringRef FDEBytes) {
1062 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1063
1064 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1065 MS->EmitIntValue(CIEOffset, 4);
1066 MS->EmitIntValue(Address, AddrSize);
1067 MS->EmitBytes(FDEBytes);
1068 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1069}
1070
Frederic Rissd3455182015-01-28 18:27:01 +00001071/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001072///
1073/// The link of the dwarf information from the object files will be
1074/// driven by the selection of 'root DIEs', which are DIEs that
1075/// describe variables or functions that are present in the linked
1076/// binary (and thus have entries in the debug map). All the debug
1077/// information that will be linked (the DIEs, but also the line
1078/// tables, ranges, ...) is derived from that set of root DIEs.
1079///
1080/// The root DIEs are identified because they contain relocations that
1081/// correspond to a debug map entry at specific places (the low_pc for
1082/// a function, the location for a variable). These relocations are
1083/// called ValidRelocs in the DwarfLinker and are gathered as a very
1084/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001085class DwarfLinker {
1086public:
Frederic Rissb9818322015-02-28 00:29:07 +00001087 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1088 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001089 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001090
Frederic Rissb8b43d52015-03-04 22:07:44 +00001091 ~DwarfLinker() {
1092 for (auto *Abbrev : Abbreviations)
1093 delete Abbrev;
1094 }
1095
Frederic Rissd3455182015-01-28 18:27:01 +00001096 /// \brief Link the contents of the DebugMap.
1097 bool link(const DebugMap &);
1098
1099private:
Frederic Riss563cba62015-01-28 22:15:14 +00001100 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001101 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001102
1103 /// \brief Called at the end of a debug object link.
1104 void endDebugObject();
1105
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001106 /// Keeps track of relocations.
1107 class RelocationManager {
1108 struct ValidReloc {
1109 uint32_t Offset;
1110 uint32_t Size;
1111 uint64_t Addend;
1112 const DebugMapObject::DebugMapEntry *Mapping;
Frederic Riss1036e642015-02-13 23:18:22 +00001113
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001114 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1115 const DebugMapObject::DebugMapEntry *Mapping)
1116 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
Frederic Riss1036e642015-02-13 23:18:22 +00001117
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001118 bool operator<(const ValidReloc &RHS) const {
1119 return Offset < RHS.Offset;
1120 }
1121 };
1122
1123 DwarfLinker &Linker;
1124
1125 /// \brief The valid relocations for the current DebugMapObject.
1126 /// This vector is sorted by relocation offset.
1127 std::vector<ValidReloc> ValidRelocs;
1128
1129 /// \brief Index into ValidRelocs of the next relocation to
1130 /// consider. As we walk the DIEs in acsending file offset and as
1131 /// ValidRelocs is sorted by file offset, keeping this index
1132 /// uptodate is all we have to do to have a cheap lookup during the
1133 /// root DIE selection and during DIE cloning.
1134 unsigned NextValidReloc;
1135
1136 public:
1137 RelocationManager(DwarfLinker &Linker)
1138 : Linker(Linker), NextValidReloc(0) {}
1139
1140 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1141 /// \brief Reset the NextValidReloc counter.
1142 void resetValidRelocs() { NextValidReloc = 0; }
1143
1144 /// \defgroup FindValidRelocations Translate debug map into a list
1145 /// of relevant relocations
1146 ///
1147 /// @{
1148 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1149 const DebugMapObject &DMO);
1150
1151 bool findValidRelocs(const object::SectionRef &Section,
1152 const object::ObjectFile &Obj,
1153 const DebugMapObject &DMO);
1154
1155 void findValidRelocsMachO(const object::SectionRef &Section,
1156 const object::MachOObjectFile &Obj,
1157 const DebugMapObject &DMO);
1158 /// @}
1159
1160 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1161 CompileUnit::DIEInfo &Info);
1162
1163 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1164 bool isLittleEndian);
Frederic Riss1036e642015-02-13 23:18:22 +00001165 };
1166
Frederic Riss84c09a52015-02-13 23:18:34 +00001167 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1168 ///
1169 /// @{
1170 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1171 /// keep. Store that information in \p CU's DIEInfo.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001172 void lookForDIEsToKeep(RelocationManager &RelocMgr,
1173 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001174 const DebugMapObject &DMO, CompileUnit &CU,
1175 unsigned Flags);
1176
1177 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1178 enum TravesalFlags {
1179 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1180 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1181 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1182 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001183 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss29eedc72015-09-11 04:17:30 +00001184 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
Frederic Riss84c09a52015-02-13 23:18:34 +00001185 };
1186
1187 /// \brief Mark the passed DIE as well as all the ones it depends on
1188 /// as kept.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001189 void keepDIEAndDenpendencies(RelocationManager &RelocMgr,
1190 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001191 CompileUnit::DIEInfo &MyInfo,
1192 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001193 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001194
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001195 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1196 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001197 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1198 unsigned Flags);
1199
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001200 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1201 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001202 CompileUnit &Unit,
1203 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1204
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001205 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1206 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001207 CompileUnit &Unit,
1208 CompileUnit::DIEInfo &MyInfo,
1209 unsigned Flags);
1210
1211 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1212 CompileUnit::DIEInfo &Info);
1213 /// @}
1214
Frederic Rissb8b43d52015-03-04 22:07:44 +00001215 /// \defgroup Linking Methods used to link the debug information
1216 ///
1217 /// @{
Frederic Rissb8b43d52015-03-04 22:07:44 +00001218
Adrian Prantl3565af42015-09-14 16:46:10 +00001219 class DIECloner {
1220 DwarfLinker &Linker;
1221 RelocationManager &RelocMgr;
1222 /// Allocator used for all the DIEValue objects.
1223 BumpPtrAllocator &DIEAlloc;
1224 MutableArrayRef<CompileUnit> CompileUnits;
1225 LinkOptions Options;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001226
Adrian Prantl3565af42015-09-14 16:46:10 +00001227 public:
1228 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1229 BumpPtrAllocator &DIEAlloc,
1230 MutableArrayRef<CompileUnit> CompileUnits, LinkOptions &Options)
1231 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1232 CompileUnits(CompileUnits), Options(Options) {}
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001233
Adrian Prantl3565af42015-09-14 16:46:10 +00001234 /// Recursively clone \p InputDIE into an tree of DIE objects
1235 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1236 /// stripped out and addresses have been rewritten according to the
1237 /// debug map.
1238 ///
1239 /// \param OutOffset is the offset the cloned DIE in the output
1240 /// compile unit.
1241 /// \param PCOffset (while cloning a function scope) is the offset
1242 /// applied to the entry point of the function to get the linked address.
1243 ///
1244 /// \returns the root of the cloned tree or null if nothing was selected.
Adrian Prantl3abe18d2015-09-14 23:27:26 +00001245 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Adrian Prantl3565af42015-09-14 16:46:10 +00001246 int64_t PCOffset, uint32_t OutOffset, unsigned Flags);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001247
Adrian Prantl3565af42015-09-14 16:46:10 +00001248 /// Construct the output DIE tree by cloning the DIEs we
1249 /// chose to keep above. If there are no valid relocs, then there's
1250 /// nothing to clone/emit.
1251 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001252
Adrian Prantl3565af42015-09-14 16:46:10 +00001253 private:
1254 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
Frederic Rissbce93ff2015-03-16 02:05:10 +00001255
Adrian Prantl3565af42015-09-14 16:46:10 +00001256 /// Information gathered and exchanged between the various
1257 /// clone*Attributes helpers about the attributes of a particular DIE.
1258 struct AttributesInfo {
1259 const char *Name, *MangledName; ///< Names.
1260 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
Frederic Riss31da3242015-03-11 18:45:52 +00001261
Adrian Prantl3565af42015-09-14 16:46:10 +00001262 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1263 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1264 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
Frederic Rissbce93ff2015-03-16 02:05:10 +00001265
Adrian Prantl3565af42015-09-14 16:46:10 +00001266 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1267 bool IsDeclaration; ///< Is this DIE only a declaration?
1268
1269 AttributesInfo()
1270 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1271 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1272 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1273 };
1274
1275 /// Helper for cloneDIE.
1276 unsigned cloneAttribute(DIE &Die,
1277 const DWARFDebugInfoEntryMinimal &InputDIE,
1278 CompileUnit &U, const DWARFFormValue &Val,
1279 const AttributeSpec AttrSpec, unsigned AttrSize,
1280 AttributesInfo &AttrInfo);
1281
1282 /// Clone a string attribute described by \p AttrSpec and add
1283 /// it to \p Die.
1284 /// \returns the size of the new attribute.
1285 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1286 const DWARFFormValue &Val,
1287 const DWARFUnit &U);
1288
1289 /// Clone an attribute referencing another DIE and add
1290 /// it to \p Die.
1291 /// \returns the size of the new attribute.
1292 unsigned
1293 cloneDieReferenceAttribute(DIE &Die,
1294 const DWARFDebugInfoEntryMinimal &InputDIE,
1295 AttributeSpec AttrSpec, unsigned AttrSize,
1296 const DWARFFormValue &Val, CompileUnit &Unit);
1297
1298 /// Clone an attribute referencing another DIE and add
1299 /// it to \p Die.
1300 /// \returns the size of the new attribute.
1301 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1302 const DWARFFormValue &Val, unsigned AttrSize);
1303
1304 /// Clone an attribute referencing another DIE and add
1305 /// it to \p Die.
1306 /// \returns the size of the new attribute.
1307 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1308 const DWARFFormValue &Val,
1309 const CompileUnit &Unit,
1310 AttributesInfo &Info);
1311
1312 /// Clone a scalar attribute and add it to \p Die.
1313 /// \returns the size of the new attribute.
1314 unsigned cloneScalarAttribute(DIE &Die,
1315 const DWARFDebugInfoEntryMinimal &InputDIE,
1316 CompileUnit &U, AttributeSpec AttrSpec,
1317 const DWARFFormValue &Val, unsigned AttrSize,
1318 AttributesInfo &Info);
1319
1320 /// Get the potential name and mangled name for the entity
1321 /// described by \p Die and store them in \Info if they are not
1322 /// already there.
1323 /// \returns is a name was found.
1324 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1325 AttributesInfo &Info);
1326
1327 /// Create a copy of abbreviation Abbrev.
1328 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
Frederic Riss31da3242015-03-11 18:45:52 +00001329 };
1330
Frederic Rissb8b43d52015-03-04 22:07:44 +00001331 /// \brief Assign an abbreviation number to \p Abbrev
1332 void AssignAbbrev(DIEAbbrev &Abbrev);
1333
1334 /// \brief FoldingSet that uniques the abbreviations.
1335 FoldingSet<DIEAbbrev> AbbreviationsSet;
1336 /// \brief Storage for the unique Abbreviations.
1337 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1338 /// be changed to a vecot of unique_ptrs.
1339 std::vector<DIEAbbrev *> Abbreviations;
1340
Frederic Riss25440872015-03-13 23:30:31 +00001341 /// \brief Compute and emit debug_ranges section for \p Unit, and
1342 /// patch the attributes referencing it.
1343 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1344
1345 /// \brief Generate and emit the DW_AT_ranges attribute for a
1346 /// compile_unit if it had one.
1347 void generateUnitRanges(CompileUnit &Unit) const;
1348
Frederic Riss63786b02015-03-15 20:45:43 +00001349 /// \brief Extract the line tables fromt he original dwarf, extract
1350 /// the relevant parts according to the linked function ranges and
1351 /// emit the result in the debug_line section.
1352 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1353
Frederic Rissbce93ff2015-03-16 02:05:10 +00001354 /// \brief Emit the accelerator entries for \p Unit.
1355 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1356
Frederic Riss5a642072015-06-05 23:06:11 +00001357 /// \brief Patch the frame info for an object file and emit it.
1358 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1359 unsigned AddressSize);
1360
Frederic Rissb8b43d52015-03-04 22:07:44 +00001361 /// \brief DIELoc objects that need to be destructed (but not freed!).
1362 std::vector<DIELoc *> DIELocs;
1363 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1364 std::vector<DIEBlock *> DIEBlocks;
1365 /// \brief Allocator used for all the DIEValue objects.
1366 BumpPtrAllocator DIEAlloc;
1367 /// @}
1368
Frederic Riss1c650942015-07-21 22:41:43 +00001369 /// ODR Contexts for that link.
1370 DeclContextTree ODRContexts;
1371
Frederic Riss1b9da422015-02-13 23:18:29 +00001372 /// \defgroup Helpers Various helper methods.
1373 ///
1374 /// @{
1375 const DWARFDebugInfoEntryMinimal *
Frederic Riss1c650942015-07-21 22:41:43 +00001376 resolveDIEReference(const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001377 const DWARFDebugInfoEntryMinimal &DIE,
1378 CompileUnit *&ReferencedCU);
1379
1380 CompileUnit *getUnitForOffset(unsigned Offset);
1381
1382 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001383 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001384
1385 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001386
1387 /// \brief Attempt to load a debug object from disk.
1388 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1389 DebugMapObject &Obj,
1390 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001391 /// @}
1392
Frederic Riss563cba62015-01-28 22:15:14 +00001393private:
Frederic Rissd3455182015-01-28 18:27:01 +00001394 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001395 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001396 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001397 std::unique_ptr<DwarfStreamer> Streamer;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001398 uint64_t OutputDebugInfoSize;
Frederic Riss563cba62015-01-28 22:15:14 +00001399
1400 /// The units of the current debug map object.
1401 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001402
1403 /// The debug map object curently under consideration.
1404 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001405
1406 /// \brief The Dwarf string pool
1407 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001408
1409 /// \brief This map is keyed by the entry PC of functions in that
1410 /// debug object and the associated value is a pair storing the
1411 /// corresponding end PC and the offset to apply to get the linked
1412 /// address.
1413 ///
1414 /// See startDebugObject() for a more complete description of its use.
1415 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001416
1417 /// \brief The CIEs that have been emitted in the output
1418 /// section. The actual CIE data serves a the key to this StringMap,
1419 /// this takes care of comparing the semantics of CIEs defined in
1420 /// different object files.
1421 StringMap<uint32_t> EmittedCIEs;
1422
1423 /// Offset of the last CIE that has been emitted in the output
1424 /// debug_frame section.
1425 uint32_t LastCIEOffset;
Frederic Rissd3455182015-01-28 18:27:01 +00001426};
1427
Frederic Riss1b9da422015-02-13 23:18:29 +00001428/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1429/// returning our CompileUnit object instead.
1430CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1431 auto CU =
1432 std::upper_bound(Units.begin(), Units.end(), Offset,
1433 [](uint32_t LHS, const CompileUnit &RHS) {
1434 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1435 });
1436 return CU != Units.end() ? &*CU : nullptr;
1437}
1438
1439/// \brief Resolve the DIE attribute reference that has been
1440/// extracted in \p RefValue. The resulting DIE migh be in another
1441/// CompileUnit which is stored into \p ReferencedCU.
1442/// \returns null if resolving fails for any reason.
1443const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
Frederic Riss1c650942015-07-21 22:41:43 +00001444 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001445 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1446 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1447 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1448
1449 if ((RefCU = getUnitForOffset(RefOffset)))
1450 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1451 return RefDie;
1452
1453 reportWarning("could not find referenced DIE", &Unit, &DIE);
1454 return nullptr;
1455}
1456
Frederic Riss1c650942015-07-21 22:41:43 +00001457/// \returns whether the passed \a Attr type might contain a DIE
1458/// reference suitable for ODR uniquing.
1459static bool isODRAttribute(uint16_t Attr) {
1460 switch (Attr) {
1461 default:
1462 return false;
1463 case dwarf::DW_AT_type:
1464 case dwarf::DW_AT_containing_type:
1465 case dwarf::DW_AT_specification:
1466 case dwarf::DW_AT_abstract_origin:
1467 case dwarf::DW_AT_import:
1468 return true;
1469 }
1470 llvm_unreachable("Improper attribute.");
1471}
1472
1473/// Set the last DIE/CU a context was seen in and, possibly invalidate
1474/// the context if it is ambiguous.
1475///
1476/// In the current implementation, we don't handle overloaded
1477/// functions well, because the argument types are not taken into
1478/// account when computing the DeclContext tree.
1479///
1480/// Some of this is mitigated byt using mangled names that do contain
1481/// the arguments types, but sometimes (eg. with function templates)
1482/// we don't have that. In that case, just do not unique anything that
1483/// refers to the contexts we are not able to distinguish.
1484///
1485/// If a context that is not a namespace appears twice in the same CU,
1486/// we know it is ambiguous. Make it invalid.
1487bool DeclContext::setLastSeenDIE(CompileUnit &U,
1488 const DWARFDebugInfoEntryMinimal *Die) {
1489 if (LastSeenCompileUnitID == U.getUniqueID()) {
1490 DWARFUnit &OrigUnit = U.getOrigUnit();
1491 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1492 U.getInfo(FirstIdx).Ctxt = nullptr;
1493 return false;
1494 }
1495
1496 LastSeenCompileUnitID = U.getUniqueID();
1497 LastSeenDIE = Die;
1498 return true;
1499}
1500
1501/// Get the child context of \a Context corresponding to \a DIE.
1502///
1503/// \returns the child context or null if we shouldn't track children
1504/// contexts. It also returns an additional bit meaning 'invalid'. An
1505/// invalid context means it shouldn't be considered for uniquing, but
1506/// its not returning null, because some children of that context
1507/// might be uniquing candidates.
1508/// FIXME: this is for dsymutil-classic compatibility, I don't think
1509/// it buys us much.
1510PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1511 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1512 NonRelocatableStringpool &StringPool) {
1513 unsigned Tag = DIE->getTag();
1514
1515 // FIXME: dsymutil-classic compat: We should bail out here if we
1516 // have a specification or an abstract_origin. We will get the
1517 // parent context wrong here.
1518
1519 switch (Tag) {
1520 default:
1521 // By default stop gathering child contexts.
1522 return PointerIntPair<DeclContext *, 1>(nullptr);
1523 case dwarf::DW_TAG_compile_unit:
1524 // FIXME: Add support for DW_TAG_module.
1525 return PointerIntPair<DeclContext *, 1>(&Context);
1526 case dwarf::DW_TAG_subprogram:
1527 // Do not unique anything inside CU local functions.
1528 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1529 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1530 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1531 dwarf::DW_AT_external, 0))
1532 return PointerIntPair<DeclContext *, 1>(nullptr);
1533 // Fallthrough
1534 case dwarf::DW_TAG_member:
1535 case dwarf::DW_TAG_namespace:
1536 case dwarf::DW_TAG_structure_type:
1537 case dwarf::DW_TAG_class_type:
1538 case dwarf::DW_TAG_union_type:
1539 case dwarf::DW_TAG_enumeration_type:
1540 case dwarf::DW_TAG_typedef:
1541 // Artificial things might be ambiguous, because they might be
1542 // created on demand. For example implicitely defined constructors
1543 // are ambiguous because of the way we identify contexts, and they
1544 // won't be generated everytime everywhere.
1545 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1546 dwarf::DW_AT_artificial, 0))
1547 return PointerIntPair<DeclContext *, 1>(nullptr);
1548 break;
1549 }
1550
1551 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1552 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1553 StringRef NameRef;
1554 StringRef ShortNameRef;
1555 StringRef FileRef;
1556
1557 if (Name)
1558 NameRef = StringPool.internString(Name);
1559 else if (Tag == dwarf::DW_TAG_namespace)
1560 // FIXME: For dsymutil-classic compatibility. I think uniquing
1561 // within anonymous namespaces is wrong. There is no ODR guarantee
1562 // there.
1563 NameRef = StringPool.internString("(anonymous namespace)");
1564
1565 if (ShortName && ShortName != Name)
1566 ShortNameRef = StringPool.internString(ShortName);
1567 else
1568 ShortNameRef = NameRef;
1569
1570 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1571 Tag != dwarf::DW_TAG_union_type &&
1572 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1573 return PointerIntPair<DeclContext *, 1>(nullptr);
1574
1575 std::string File;
1576 unsigned Line = 0;
1577 unsigned ByteSize = 0;
1578
1579 // Gather some discriminating data about the DeclContext we will be
1580 // creating: File, line number and byte size. This shouldn't be
1581 // necessary, because the ODR is just about names, but given that we
1582 // do some approximations with overloaded functions and anonymous
1583 // namespaces, use these additional data points to make the process safer.
1584 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1585 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1586 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1587 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1588 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1589 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1590 &U.getOrigUnit())) {
1591 // FIXME: dsymutil-classic compatibility. I'd rather not
1592 // unique anything in anonymous namespaces, but if we do, then
1593 // verify that the file and line correspond.
1594 if (!Name && Tag == dwarf::DW_TAG_namespace)
1595 FileNum = 1;
1596
1597 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1598 // instead of "" would allow more uniquing, but for now, do
1599 // it this way to match dsymutil-classic.
1600 if (LT->getFileNameByIndex(
1601 FileNum, "",
1602 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1603 File)) {
1604 Line = DIE->getAttributeValueAsUnsignedConstant(
1605 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1606#ifdef HAVE_REALPATH
1607 // Cache the resolved paths, because calling realpath is expansive.
1608 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1609 File = ResolvedPath;
1610 } else {
1611 char RealPath[PATH_MAX + 1];
1612 RealPath[PATH_MAX] = 0;
1613 if (::realpath(File.c_str(), RealPath))
1614 File = RealPath;
1615 U.setResolvedPath(FileNum, File);
1616 }
1617#endif
1618 FileRef = StringPool.internString(File);
1619 }
1620 }
1621 }
1622 }
1623
1624 if (!Line && NameRef.empty())
1625 return PointerIntPair<DeclContext *, 1>(nullptr);
1626
1627 // FIXME: dsymutil-classic compat won't unique the same type
1628 // presented once as a struct and once as a class. Use the Tag in
1629 // the fully qualified name hash to get the same effect.
1630 // We hash NameRef, which is the mangled name, in order to get most
1631 // overloaded functions resolvec correctly.
1632 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1633
1634 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1635 // use the filename.
1636 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1637 Hash = hash_combine(Hash, FileRef);
1638
1639 // Now look if this context already exists.
1640 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1641 auto ContextIter = Contexts.find(&Key);
1642
1643 if (ContextIter == Contexts.end()) {
1644 // The context wasn't found.
1645 bool Inserted;
1646 DeclContext *NewContext =
1647 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1648 Context, DIE, U.getUniqueID());
1649 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1650 assert(Inserted && "Failed to insert DeclContext");
1651 (void)Inserted;
1652 } else if (Tag != dwarf::DW_TAG_namespace &&
1653 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1654 // The context was found, but it is ambiguous with another context
1655 // in the same file. Mark it invalid.
1656 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1657 }
1658
1659 assert(ContextIter != Contexts.end());
1660 // FIXME: dsymutil-classic compatibility. Union types aren't
1661 // uniques, but their children might be.
1662 if ((Tag == dwarf::DW_TAG_subprogram &&
1663 Context.getTag() != dwarf::DW_TAG_structure_type &&
1664 Context.getTag() != dwarf::DW_TAG_class_type) ||
1665 (Tag == dwarf::DW_TAG_union_type))
1666 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1667
1668 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1669}
1670
Adrian Prantl3565af42015-09-14 16:46:10 +00001671bool DwarfLinker::DIECloner::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1672 DWARFUnit &U, AttributesInfo &Info) {
1673 // FIXME: a bit wasteful as the first getName might return the
Frederic Rissbce93ff2015-03-16 02:05:10 +00001674 // short name.
1675 if (!Info.MangledName &&
1676 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001677 Info.MangledNameOffset =
1678 Linker.StringPool.getStringOffset(Info.MangledName);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001679
1680 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001681 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001682
1683 return Info.Name || Info.MangledName;
1684}
1685
Frederic Riss1b9da422015-02-13 23:18:29 +00001686/// \brief Report a warning to the user, optionaly including
1687/// information about a specific \p DIE related to the warning.
1688void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001689 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001690 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001691 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001692 Context = CurrentDebugObject->getObjectFilename();
1693 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001694
Frederic Rissb9818322015-02-28 00:29:07 +00001695 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001696 return;
1697
1698 errs() << " in DIE:\n";
1699 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1700 6 /* Indent */);
1701}
1702
Frederic Rissc99ea202015-02-28 00:29:11 +00001703bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1704 if (Options.NoOutput)
1705 return true;
1706
Frederic Rissb52cf522015-02-28 00:42:37 +00001707 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001708 return Streamer->init(TheTriple, OutputFilename);
1709}
1710
Frederic Riss563cba62015-01-28 22:15:14 +00001711/// \brief Recursive helper to gather the child->parent relationships in the
1712/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001713static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
Frederic Riss1c650942015-07-21 22:41:43 +00001714 unsigned ParentIdx, CompileUnit &CU,
1715 DeclContext *CurrentDeclContext,
1716 NonRelocatableStringpool &StringPool,
1717 DeclContextTree &Contexts) {
Frederic Riss563cba62015-01-28 22:15:14 +00001718 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001719 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1720
1721 Info.ParentIdx = ParentIdx;
1722 if (CU.hasODR()) {
1723 if (CurrentDeclContext) {
1724 auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1725 DIE, CU, StringPool);
1726 CurrentDeclContext = PtrInvalidPair.getPointer();
1727 Info.Ctxt =
1728 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1729 } else
1730 Info.Ctxt = CurrentDeclContext = nullptr;
1731 }
Frederic Riss563cba62015-01-28 22:15:14 +00001732
1733 if (DIE->hasChildren())
1734 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1735 Child = Child->getSibling())
Frederic Riss1c650942015-07-21 22:41:43 +00001736 gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1737 Contexts);
Frederic Riss563cba62015-01-28 22:15:14 +00001738}
1739
Frederic Riss84c09a52015-02-13 23:18:34 +00001740static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1741 switch (Tag) {
1742 default:
1743 return false;
1744 case dwarf::DW_TAG_subprogram:
1745 case dwarf::DW_TAG_lexical_block:
1746 case dwarf::DW_TAG_subroutine_type:
1747 case dwarf::DW_TAG_structure_type:
1748 case dwarf::DW_TAG_class_type:
1749 case dwarf::DW_TAG_union_type:
1750 return true;
1751 }
1752 llvm_unreachable("Invalid Tag");
1753}
1754
Frederic Riss1c650942015-07-21 22:41:43 +00001755static unsigned getRefAddrSize(const DWARFUnit &U) {
1756 if (U.getVersion() == 2)
1757 return U.getAddressByteSize();
1758 return 4;
1759}
1760
Frederic Riss63786b02015-03-15 20:45:43 +00001761void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001762 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss63786b02015-03-15 20:45:43 +00001763 // Iterate over the debug map entries and put all the ones that are
1764 // functions (because they have a size) into the Ranges map. This
1765 // map is very similar to the FunctionRanges that are stored in each
1766 // unit, with 2 notable differences:
1767 // - obviously this one is global, while the other ones are per-unit.
1768 // - this one contains not only the functions described in the DIE
1769 // tree, but also the ones that are only in the debug map.
1770 // The latter information is required to reproduce dsymutil's logic
1771 // while linking line tables. The cases where this information
1772 // matters look like bugs that need to be investigated, but for now
1773 // we need to reproduce dsymutil's behavior.
1774 // FIXME: Once we understood exactly if that information is needed,
1775 // maybe totally remove this (or try to use it to do a real
1776 // -gline-tables-only on Darwin.
1777 for (const auto &Entry : Obj.symbols()) {
1778 const auto &Mapping = Entry.getValue();
1779 if (Mapping.Size)
1780 Ranges[Mapping.ObjectAddress] = std::make_pair(
1781 Mapping.ObjectAddress + Mapping.Size,
1782 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1783 }
Frederic Riss563cba62015-01-28 22:15:14 +00001784}
1785
Frederic Riss1036e642015-02-13 23:18:22 +00001786void DwarfLinker::endDebugObject() {
1787 Units.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001788 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001789
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001790 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1791 (*I)->~DIEBlock();
1792 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1793 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001794
1795 DIEBlocks.clear();
1796 DIELocs.clear();
1797 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001798}
1799
1800/// \brief Iterate over the relocations of the given \p Section and
1801/// store the ones that correspond to debug map entries into the
1802/// ValidRelocs array.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001803void DwarfLinker::RelocationManager::
1804findValidRelocsMachO(const object::SectionRef &Section,
1805 const object::MachOObjectFile &Obj,
1806 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001807 StringRef Contents;
1808 Section.getContents(Contents);
1809 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1810
1811 for (const object::RelocationRef &Reloc : Section.relocations()) {
1812 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1813 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1814 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001815 uint64_t Offset64 = Reloc.getOffset();
1816 if ((RelocSize != 4 && RelocSize != 8)) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001817 Linker.reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001818 continue;
1819 }
1820 uint32_t Offset = Offset64;
1821 // Mach-o uses REL relocations, the addend is at the relocation offset.
1822 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1823
1824 auto Sym = Reloc.getSymbol();
1825 if (Sym != Obj.symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001826 ErrorOr<StringRef> SymbolName = Sym->getName();
1827 if (!SymbolName) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001828 Linker.reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001829 continue;
1830 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001831 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001832 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1833 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1834 // Do not store the addend. The addend was the address of the
1835 // symbol in the object file, the address in the binary that is
1836 // stored in the debug map doesn't need to be offseted.
1837 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1838 }
1839 }
1840}
1841
1842/// \brief Dispatch the valid relocation finding logic to the
1843/// appropriate handler depending on the object file format.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001844bool DwarfLinker::RelocationManager::findValidRelocs(
1845 const object::SectionRef &Section, const object::ObjectFile &Obj,
1846 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001847 // Dispatch to the right handler depending on the file type.
1848 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1849 findValidRelocsMachO(Section, *MachOObj, DMO);
1850 else
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001851 Linker.reportWarning(Twine("unsupported object file type: ") +
1852 Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001853
1854 if (ValidRelocs.empty())
1855 return false;
1856
1857 // Sort the relocations by offset. We will walk the DIEs linearly in
1858 // the file, this allows us to just keep an index in the relocation
1859 // array that we advance during our walk, rather than resorting to
1860 // some associative container. See DwarfLinker::NextValidReloc.
1861 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1862 return true;
1863}
1864
1865/// \brief Look for relocations in the debug_info section that match
1866/// entries in the debug map. These relocations will drive the Dwarf
1867/// link by indicating which DIEs refer to symbols present in the
1868/// linked binary.
1869/// \returns wether there are any valid relocations in the debug info.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001870bool DwarfLinker::RelocationManager::
1871findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1872 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001873 // Find the debug_info section.
1874 for (const object::SectionRef &Section : Obj.sections()) {
1875 StringRef SectionName;
1876 Section.getName(SectionName);
1877 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1878 if (SectionName != "debug_info")
1879 continue;
1880 return findValidRelocs(Section, Obj, DMO);
1881 }
1882 return false;
1883}
Frederic Riss563cba62015-01-28 22:15:14 +00001884
Frederic Riss84c09a52015-02-13 23:18:34 +00001885/// \brief Checks that there is a relocation against an actual debug
1886/// map entry between \p StartOffset and \p NextOffset.
1887///
1888/// This function must be called with offsets in strictly ascending
1889/// order because it never looks back at relocations it already 'went past'.
1890/// \returns true and sets Info.InDebugMap if it is the case.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001891bool DwarfLinker::RelocationManager::
1892hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1893 CompileUnit::DIEInfo &Info) {
Frederic Riss84c09a52015-02-13 23:18:34 +00001894 assert(NextValidReloc == 0 ||
1895 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1896 if (NextValidReloc >= ValidRelocs.size())
1897 return false;
1898
1899 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1900
1901 // We might need to skip some relocs that we didn't consider. For
1902 // example the high_pc of a discarded DIE might contain a reloc that
1903 // is in the list because it actually corresponds to the start of a
1904 // function that is in the debug map.
1905 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1906 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1907
1908 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1909 return false;
1910
1911 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001912 const auto &Mapping = ValidReloc.Mapping->getValue();
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001913 if (Linker.Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001914 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1915 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001916 uint64_t(Mapping.ObjectAddress),
1917 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001918
Frederic Rissf37964c2015-06-05 20:27:07 +00001919 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1920 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001921 Info.InDebugMap = true;
1922 return true;
1923}
1924
1925/// \brief Get the starting and ending (exclusive) offset for the
1926/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1927/// supposed to point to the position of the first attribute described
1928/// by \p Abbrev.
1929/// \return [StartOffset, EndOffset) as a pair.
1930static std::pair<uint32_t, uint32_t>
1931getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1932 unsigned Offset, const DWARFUnit &Unit) {
1933 DataExtractor Data = Unit.getDebugInfoExtractor();
1934
1935 for (unsigned i = 0; i < Idx; ++i)
1936 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1937
1938 uint32_t End = Offset;
1939 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1940
1941 return std::make_pair(Offset, End);
1942}
1943
1944/// \brief Check if a variable describing DIE should be kept.
1945/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001946unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
1947 const DWARFDebugInfoEntryMinimal &DIE,
1948 CompileUnit &Unit,
1949 CompileUnit::DIEInfo &MyInfo,
1950 unsigned Flags) {
Frederic Riss84c09a52015-02-13 23:18:34 +00001951 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1952
1953 // Global variables with constant value can always be kept.
1954 if (!(Flags & TF_InFunctionScope) &&
1955 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1956 MyInfo.InDebugMap = true;
1957 return Flags | TF_Keep;
1958 }
1959
1960 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1961 if (LocationIdx == -1U)
1962 return Flags;
1963
1964 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1965 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1966 uint32_t LocationOffset, LocationEndOffset;
1967 std::tie(LocationOffset, LocationEndOffset) =
1968 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1969
1970 // See if there is a relocation to a valid debug map entry inside
1971 // this variable's location. The order is important here. We want to
1972 // always check in the variable has a valid relocation, so that the
1973 // DIEInfo is filled. However, we don't want a static variable in a
1974 // function to force us to keep the enclosing function.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001975 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
Frederic Riss84c09a52015-02-13 23:18:34 +00001976 (Flags & TF_InFunctionScope))
1977 return Flags;
1978
Frederic Rissb9818322015-02-28 00:29:07 +00001979 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001980 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1981
1982 return Flags | TF_Keep;
1983}
1984
1985/// \brief Check if a function describing DIE should be kept.
1986/// \returns updated TraversalFlags.
1987unsigned DwarfLinker::shouldKeepSubprogramDIE(
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001988 RelocationManager &RelocMgr,
Frederic Riss84c09a52015-02-13 23:18:34 +00001989 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1990 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1991 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1992
1993 Flags |= TF_InFunctionScope;
1994
1995 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1996 if (LowPcIdx == -1U)
1997 return Flags;
1998
1999 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2000 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2001 uint32_t LowPcOffset, LowPcEndOffset;
2002 std::tie(LowPcOffset, LowPcEndOffset) =
2003 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2004
2005 uint64_t LowPc =
2006 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2007 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2008 if (LowPc == -1ULL ||
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002009 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
Frederic Riss84c09a52015-02-13 23:18:34 +00002010 return Flags;
2011
Frederic Rissb9818322015-02-28 00:29:07 +00002012 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002013 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2014
Frederic Riss1af75f72015-03-12 18:45:10 +00002015 Flags |= TF_Keep;
2016
2017 DWARFFormValue HighPcValue;
2018 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2019 reportWarning("Function without high_pc. Range will be discarded.\n",
2020 &OrigUnit, &DIE);
2021 return Flags;
2022 }
2023
2024 uint64_t HighPc;
2025 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2026 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2027 } else {
2028 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2029 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2030 }
2031
Frederic Riss63786b02015-03-15 20:45:43 +00002032 // Replace the debug map range with a more accurate one.
2033 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002034 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2035 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002036}
2037
2038/// \brief Check if a DIE should be kept.
2039/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002040unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2041 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00002042 CompileUnit &Unit,
2043 CompileUnit::DIEInfo &MyInfo,
2044 unsigned Flags) {
2045 switch (DIE.getTag()) {
2046 case dwarf::DW_TAG_constant:
2047 case dwarf::DW_TAG_variable:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002048 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002049 case dwarf::DW_TAG_subprogram:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002050 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002051 case dwarf::DW_TAG_module:
2052 case dwarf::DW_TAG_imported_module:
2053 case dwarf::DW_TAG_imported_declaration:
2054 case dwarf::DW_TAG_imported_unit:
2055 // We always want to keep these.
2056 return Flags | TF_Keep;
2057 }
2058
2059 return Flags;
2060}
2061
Frederic Riss84c09a52015-02-13 23:18:34 +00002062/// \brief Mark the passed DIE as well as all the ones it depends on
2063/// as kept.
2064///
2065/// This function is called by lookForDIEsToKeep on DIEs that are
2066/// newly discovered to be needed in the link. It recursively calls
2067/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2068/// TraversalFlags to inform it that it's not doing the primary DIE
2069/// tree walk.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002070void DwarfLinker::keepDIEAndDenpendencies(RelocationManager &RelocMgr,
2071 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002072 CompileUnit::DIEInfo &MyInfo,
2073 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002074 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002075 const DWARFUnit &Unit = CU.getOrigUnit();
2076 MyInfo.Keep = true;
2077
2078 // First mark all the parent chain as kept.
2079 unsigned AncestorIdx = MyInfo.ParentIdx;
2080 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002081 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002082 lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002083 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002084 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2085 }
2086
2087 // Then we need to mark all the DIEs referenced by this DIE's
2088 // attributes as kept.
2089 DataExtractor Data = Unit.getDebugInfoExtractor();
Frederic Riss36c3cb82015-09-11 04:17:25 +00002090 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2091 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
Frederic Riss84c09a52015-02-13 23:18:34 +00002092
2093 // Mark all DIEs referenced through atttributes as kept.
2094 for (const auto &AttrSpec : Abbrev->attributes()) {
2095 DWARFFormValue Val(AttrSpec.Form);
2096
2097 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2098 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2099 continue;
2100 }
2101
2102 Val.extractValue(Data, &Offset, &Unit);
2103 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002104 if (const auto *RefDIE =
Frederic Riss36c3cb82015-09-11 04:17:25 +00002105 resolveDIEReference(Val, Unit, Die, ReferencedCU)) {
Frederic Riss1c650942015-07-21 22:41:43 +00002106 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2107 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2108 // If the referenced DIE has a DeclContext that has already been
2109 // emitted, then do not keep the one in this CU. We'll link to
2110 // the canonical DIE in cloneDieReferenceAttribute.
2111 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2112 // be necessary and could be advantageously replaced by
2113 // ReferencedCU->hasODR() && CU.hasODR().
2114 // FIXME: compatibility with dsymutil-classic. There is no
2115 // reason not to unique ref_addr references.
2116 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2117 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2118 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2119 continue;
2120
2121 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002122 lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002123 TF_Keep | TF_DependencyWalk | ODRFlag);
2124 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002125 }
2126}
2127
2128/// \brief Recursively walk the \p DIE tree and look for DIEs to
2129/// keep. Store that information in \p CU's DIEInfo.
2130///
2131/// This function is the entry point of the DIE selection
2132/// algorithm. It is expected to walk the DIE tree in file order and
2133/// (though the mediation of its helper) call hasValidRelocation() on
2134/// each DIE that might be a 'root DIE' (See DwarfLinker class
2135/// comment).
2136/// While walking the dependencies of root DIEs, this function is
2137/// also called, but during these dependency walks the file order is
2138/// not respected. The TF_DependencyWalk flag tells us which kind of
2139/// traversal we are currently doing.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002140void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2141 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002142 const DebugMapObject &DMO, CompileUnit &CU,
2143 unsigned Flags) {
Frederic Riss36c3cb82015-09-11 04:17:25 +00002144 unsigned Idx = CU.getOrigUnit().getDIEIndex(&Die);
Frederic Riss84c09a52015-02-13 23:18:34 +00002145 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2146 bool AlreadyKept = MyInfo.Keep;
2147
2148 // If the Keep flag is set, we are marking a required DIE's
2149 // dependencies. If our target is already marked as kept, we're all
2150 // set.
2151 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2152 return;
2153
2154 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2155 // because it would screw up the relocation finding logic.
2156 if (!(Flags & TF_DependencyWalk))
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002157 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002158
2159 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002160 if (!AlreadyKept && (Flags & TF_Keep)) {
2161 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002162 keepDIEAndDenpendencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
Frederic Riss1c650942015-07-21 22:41:43 +00002163 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002164 // The TF_ParentWalk flag tells us that we are currently walking up
2165 // the parent chain of a required DIE, and we don't want to mark all
2166 // the children of the parents as kept (consider for example a
2167 // DW_TAG_namespace node in the parent chain). There are however a
2168 // set of DIE types for which we want to ignore that directive and still
2169 // walk their children.
Frederic Riss36c3cb82015-09-11 04:17:25 +00002170 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
Frederic Riss84c09a52015-02-13 23:18:34 +00002171 Flags &= ~TF_ParentWalk;
2172
Frederic Riss36c3cb82015-09-11 04:17:25 +00002173 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
Frederic Riss84c09a52015-02-13 23:18:34 +00002174 return;
2175
Frederic Riss36c3cb82015-09-11 04:17:25 +00002176 for (auto *Child = Die.getFirstChild(); Child && !Child->isNULL();
Frederic Riss84c09a52015-02-13 23:18:34 +00002177 Child = Child->getSibling())
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002178 lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002179}
2180
Frederic Rissb8b43d52015-03-04 22:07:44 +00002181/// \brief Assign an abbreviation numer to \p Abbrev.
2182///
2183/// Our DIEs get freed after every DebugMapObject has been processed,
2184/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2185/// the instances hold by the DIEs. When we encounter an abbreviation
2186/// that we don't know, we create a permanent copy of it.
2187void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2188 // Check the set for priors.
2189 FoldingSetNodeID ID;
2190 Abbrev.Profile(ID);
2191 void *InsertToken;
2192 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2193
2194 // If it's newly added.
2195 if (InSet) {
2196 // Assign existing abbreviation number.
2197 Abbrev.setNumber(InSet->getNumber());
2198 } else {
2199 // Add to abbreviation list.
2200 Abbreviations.push_back(
2201 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2202 for (const auto &Attr : Abbrev.getData())
2203 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2204 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2205 // Assign the unique abbreviation number.
2206 Abbrev.setNumber(Abbreviations.size());
2207 Abbreviations.back()->setNumber(Abbreviations.size());
2208 }
2209}
2210
Adrian Prantl3565af42015-09-14 16:46:10 +00002211unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2212 AttributeSpec AttrSpec,
2213 const DWARFFormValue &Val,
2214 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002215 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002216 const char *String = *Val.getAsCString(&U);
Adrian Prantl3565af42015-09-14 16:46:10 +00002217 unsigned Offset = Linker.StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002218 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002219 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002220 return 4;
2221}
2222
Adrian Prantl3565af42015-09-14 16:46:10 +00002223unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
Frederic Riss9833de62015-03-06 23:22:53 +00002224 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2225 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002226 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002227 const DWARFUnit &U = Unit.getOrigUnit();
2228 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002229 DIE *NewRefDie = nullptr;
2230 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002231 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002232
Frederic Riss1c650942015-07-21 22:41:43 +00002233 const DWARFDebugInfoEntryMinimal *RefDie =
Adrian Prantl3565af42015-09-14 16:46:10 +00002234 Linker.resolveDIEReference(Val, U, InputDIE, RefUnit);
Frederic Riss1c650942015-07-21 22:41:43 +00002235
2236 // If the referenced DIE is not found, drop the attribute.
2237 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002238 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002239
2240 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2241 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002242
2243 // If we already have emitted an equivalent DeclContext, just point
2244 // at it.
2245 if (isODRAttribute(AttrSpec.Attr)) {
2246 Ctxt = RefInfo.Ctxt;
2247 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2248 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2249 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2250 dwarf::DW_FORM_ref_addr, Attr);
2251 return getRefAddrSize(U);
2252 }
2253 }
2254
Frederic Riss9833de62015-03-06 23:22:53 +00002255 if (!RefInfo.Clone) {
2256 assert(Ref > InputDIE.getOffset());
2257 // We haven't cloned this DIE yet. Just create an empty one and
2258 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002259 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002260 }
2261 NewRefDie = RefInfo.Clone;
2262
Frederic Riss1c650942015-07-21 22:41:43 +00002263 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2264 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002265 // We cannot currently rely on a DIEEntry to emit ref_addr
2266 // references, because the implementation calls back to DwarfDebug
2267 // to find the unit offset. (We don't have a DwarfDebug)
2268 // FIXME: we should be able to design DIEEntry reliance on
2269 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002270 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002271 if (Ref < InputDIE.getOffset()) {
2272 // We must have already cloned that DIE.
2273 uint32_t NewRefOffset =
2274 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002275 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002276 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2277 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002278 } else {
2279 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002280 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002281 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002282 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002283 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2284 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002285 }
Frederic Riss1c650942015-07-21 22:41:43 +00002286 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002287 }
2288
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002289 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2290 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002291 return AttrSize;
2292}
2293
Adrian Prantl3565af42015-09-14 16:46:10 +00002294unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2295 AttributeSpec AttrSpec,
2296 const DWARFFormValue &Val,
2297 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002298 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002299 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002300 DIELoc *Loc = nullptr;
2301 DIEBlock *Block = nullptr;
2302 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002303 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002304 Loc = new (DIEAlloc) DIELoc;
Adrian Prantl3565af42015-09-14 16:46:10 +00002305 Linker.DIELocs.push_back(Loc);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002306 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002307 Block = new (DIEAlloc) DIEBlock;
Adrian Prantl3565af42015-09-14 16:46:10 +00002308 Linker.DIEBlocks.push_back(Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002309 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002310 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2311 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002312
2313 if (Loc)
2314 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2315 dwarf::Form(AttrSpec.Form), Loc);
2316 else
2317 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2318 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002319 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2320 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002321 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2322 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002323 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2324 // the DIE class, this if could be replaced by
2325 // Attr->setSize(Bytes.size()).
Adrian Prantl3565af42015-09-14 16:46:10 +00002326 if (Linker.Streamer) {
2327 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002328 if (Loc)
Adrian Prantl3565af42015-09-14 16:46:10 +00002329 Loc->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002330 else
Adrian Prantl3565af42015-09-14 16:46:10 +00002331 Block->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002332 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002333 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002334 return AttrSize;
2335}
2336
Adrian Prantl3565af42015-09-14 16:46:10 +00002337unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2338 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2339 const CompileUnit &Unit, AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002340 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002341 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2342 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2343 Die.getTag() == dwarf::DW_TAG_lexical_block)
Frederic Riss7b5563a2015-08-31 01:43:14 +00002344 // The low_pc of a block or inline subroutine might get
2345 // relocated because it happens to match the low_pc of the
2346 // enclosing subprogram. To prevent issues with that, always use
2347 // the low_pc from the input DIE if relocations have been applied.
2348 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2349 Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002350 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2351 Addr = Unit.getLowPc();
2352 if (Addr == UINT64_MAX)
2353 return 0;
2354 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002355 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002356 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002357 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2358 if (uint64_t HighPc = Unit.getHighPc())
2359 Addr = HighPc;
2360 else
2361 return 0;
2362 } else
2363 // If we have a high_pc recorded for the input DIE, use
2364 // it. Otherwise (when no relocations where applied) just use the
2365 // one we just decoded.
2366 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002367 }
2368
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002369 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002370 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002371 return Unit.getOrigUnit().getAddressByteSize();
2372}
2373
Adrian Prantl3565af42015-09-14 16:46:10 +00002374unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002375 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002376 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002377 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002378 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002379 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2380 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2381 if (Unit.getLowPc() == -1ULL)
2382 return 0;
2383 // Dwarf >= 4 high_pc is an size, not an address.
2384 Value = Unit.getHighPc() - Unit.getLowPc();
2385 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002386 Value = *Val.getAsSectionOffset();
2387 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2388 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002389 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2390 Value = *OptionalValue;
2391 else {
Adrian Prantl3565af42015-09-14 16:46:10 +00002392 Linker.reportWarning(
2393 "Unsupported scalar attribute form. Dropping attribute.",
2394 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002395 return 0;
2396 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002397 PatchLocation Patch =
2398 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2399 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002400 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002401 Unit.noteRangeAttribute(Die, Patch);
Frederic Riss29eedc72015-09-11 04:17:30 +00002402
Frederic Rissdfb97902015-03-14 15:49:07 +00002403 // A more generic way to check for location attributes would be
2404 // nice, but it's very unlikely that any other attribute needs a
2405 // location list.
2406 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2407 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002408 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002409 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2410 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002411
Frederic Rissb8b43d52015-03-04 22:07:44 +00002412 return AttrSize;
2413}
2414
2415/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2416/// value \p Val, and add it to \p Die.
2417/// \returns the size of the cloned attribute.
Adrian Prantl3565af42015-09-14 16:46:10 +00002418unsigned DwarfLinker::DIECloner::cloneAttribute(
2419 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2420 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2421 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002422 const DWARFUnit &U = Unit.getOrigUnit();
2423
2424 switch (AttrSpec.Form) {
2425 case dwarf::DW_FORM_strp:
2426 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002427 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002428 case dwarf::DW_FORM_ref_addr:
2429 case dwarf::DW_FORM_ref1:
2430 case dwarf::DW_FORM_ref2:
2431 case dwarf::DW_FORM_ref4:
2432 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002433 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002434 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002435 case dwarf::DW_FORM_block:
2436 case dwarf::DW_FORM_block1:
2437 case dwarf::DW_FORM_block2:
2438 case dwarf::DW_FORM_block4:
2439 case dwarf::DW_FORM_exprloc:
2440 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2441 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002442 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002443 case dwarf::DW_FORM_data1:
2444 case dwarf::DW_FORM_data2:
2445 case dwarf::DW_FORM_data4:
2446 case dwarf::DW_FORM_data8:
2447 case dwarf::DW_FORM_udata:
2448 case dwarf::DW_FORM_sdata:
2449 case dwarf::DW_FORM_sec_offset:
2450 case dwarf::DW_FORM_flag:
2451 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002452 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2453 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002454 default:
Adrian Prantl3565af42015-09-14 16:46:10 +00002455 Linker.reportWarning(
2456 "Unsupported attribute form in cloneAttribute. Dropping.", &U,
2457 &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002458 }
2459
2460 return 0;
2461}
2462
Frederic Riss23e20e92015-03-07 01:25:09 +00002463/// \brief Apply the valid relocations found by findValidRelocs() to
2464/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2465/// in the debug_info section.
2466///
2467/// Like for findValidRelocs(), this function must be called with
2468/// monotonic \p BaseOffset values.
2469///
2470/// \returns wether any reloc has been applied.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002471bool DwarfLinker::RelocationManager::
2472applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2473 bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002474 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002475 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2476 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002477 if (NextValidReloc >= ValidRelocs.size())
2478 return false;
2479
2480 // Skip relocs that haven't been applied.
2481 while (NextValidReloc < ValidRelocs.size() &&
2482 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2483 ++NextValidReloc;
2484
2485 bool Applied = false;
2486 uint64_t EndOffset = BaseOffset + Data.size();
2487 while (NextValidReloc < ValidRelocs.size() &&
2488 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2489 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2490 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2491 assert(ValidReloc.Offset - BaseOffset < Data.size());
2492 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2493 char Buf[8];
2494 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2495 Value += ValidReloc.Addend;
2496 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2497 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2498 Buf[i] = uint8_t(Value >> (Index * 8));
2499 }
2500 assert(ValidReloc.Size <= sizeof(Buf));
2501 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2502 Applied = true;
2503 }
2504
2505 return Applied;
2506}
2507
Frederic Rissbce93ff2015-03-16 02:05:10 +00002508static bool isTypeTag(uint16_t Tag) {
2509 switch (Tag) {
2510 case dwarf::DW_TAG_array_type:
2511 case dwarf::DW_TAG_class_type:
2512 case dwarf::DW_TAG_enumeration_type:
2513 case dwarf::DW_TAG_pointer_type:
2514 case dwarf::DW_TAG_reference_type:
2515 case dwarf::DW_TAG_string_type:
2516 case dwarf::DW_TAG_structure_type:
2517 case dwarf::DW_TAG_subroutine_type:
2518 case dwarf::DW_TAG_typedef:
2519 case dwarf::DW_TAG_union_type:
2520 case dwarf::DW_TAG_ptr_to_member_type:
2521 case dwarf::DW_TAG_set_type:
2522 case dwarf::DW_TAG_subrange_type:
2523 case dwarf::DW_TAG_base_type:
2524 case dwarf::DW_TAG_const_type:
2525 case dwarf::DW_TAG_constant:
2526 case dwarf::DW_TAG_file_type:
2527 case dwarf::DW_TAG_namelist:
2528 case dwarf::DW_TAG_packed_type:
2529 case dwarf::DW_TAG_volatile_type:
2530 case dwarf::DW_TAG_restrict_type:
2531 case dwarf::DW_TAG_interface_type:
2532 case dwarf::DW_TAG_unspecified_type:
2533 case dwarf::DW_TAG_shared_type:
2534 return true;
2535 default:
2536 break;
2537 }
2538 return false;
2539}
2540
Frederic Riss29eedc72015-09-11 04:17:30 +00002541static bool
2542shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2543 uint16_t Tag, bool InDebugMap, bool SkipPC,
2544 bool InFunctionScope) {
2545 switch (AttrSpec.Attr) {
2546 default:
2547 return false;
2548 case dwarf::DW_AT_low_pc:
2549 case dwarf::DW_AT_high_pc:
2550 case dwarf::DW_AT_ranges:
2551 return SkipPC;
2552 case dwarf::DW_AT_location:
2553 case dwarf::DW_AT_frame_base:
2554 // FIXME: for some reason dsymutil-classic keeps the location
2555 // attributes when they are of block type (ie. not location
2556 // lists). This is totally wrong for globals where we will keep a
2557 // wrong address. It is mostly harmless for locals, but there is
2558 // no point in keeping these anyway when the function wasn't linked.
2559 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2560 !InDebugMap)) &&
2561 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2562 }
2563}
2564
Adrian Prantl3565af42015-09-14 16:46:10 +00002565DIE *DwarfLinker::DIECloner::cloneDIE(
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002566 const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2567 int64_t PCOffset, uint32_t OutOffset, unsigned Flags) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002568 DWARFUnit &U = Unit.getOrigUnit();
2569 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002570 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002571
2572 // Should the DIE appear in the output?
2573 if (!Unit.getInfo(Idx).Keep)
2574 return nullptr;
2575
2576 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002577 // The DIE might have been already created by a forward reference
2578 // (see cloneDieReferenceAttribute()).
2579 DIE *Die = Info.Clone;
2580 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002581 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002582 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002583 Die->setOffset(OutOffset);
Frederic Riss1c650942015-07-21 22:41:43 +00002584 if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2585 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2586 !Info.Ctxt->getCanonicalDIEOffset()) {
2587 // We are about to emit a DIE that is the root of its own valid
2588 // DeclContext tree. Make the current offset the canonical offset
2589 // for this context.
2590 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2591 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002592
2593 // Extract and clone every attribute.
2594 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002595 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002596 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002597
2598 // We could copy the data only if we need to aply a relocation to
2599 // it. After testing, it seems there is no performance downside to
2600 // doing the copy unconditionally, and it makes the code simpler.
2601 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2602 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2603 // Modify the copy with relocated addresses.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002604 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
Frederic Riss31da3242015-03-11 18:45:52 +00002605 // If we applied relocations, we store the value of high_pc that was
2606 // potentially stored in the input DIE. If high_pc is an address
2607 // (Dwarf version == 2), then it might have been relocated to a
2608 // totally unrelated value (because the end address in the object
2609 // file might be start address of another function which got moved
2610 // independantly by the linker). The computation of the actual
2611 // high_pc value is done in cloneAddressAttribute().
2612 AttrInfo.OrigHighPc =
2613 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
Frederic Riss7b5563a2015-08-31 01:43:14 +00002614 // Also store the low_pc. It might get relocated in an
2615 // inline_subprogram that happens at the beginning of its
2616 // inlining function.
2617 AttrInfo.OrigLowPc =
2618 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
Frederic Riss31da3242015-03-11 18:45:52 +00002619 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002620
2621 // Reset the Offset to 0 as we will be working on the local copy of
2622 // the data.
2623 Offset = 0;
2624
Frederic Rissb8b43d52015-03-04 22:07:44 +00002625 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2626 Offset += getULEB128Size(Abbrev->getCode());
2627
Frederic Riss31da3242015-03-11 18:45:52 +00002628 // We are entering a subprogram. Get and propagate the PCOffset.
2629 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2630 PCOffset = Info.AddrAdjust;
2631 AttrInfo.PCOffset = PCOffset;
2632
Frederic Riss29eedc72015-09-11 04:17:30 +00002633 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2634 Flags |= TF_InFunctionScope;
2635 if (!Info.InDebugMap)
2636 Flags |= TF_SkipPC;
2637 }
2638
2639 bool Copied = false;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002640 for (const auto &AttrSpec : Abbrev->attributes()) {
Frederic Riss29eedc72015-09-11 04:17:30 +00002641 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2642 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2643 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2644 // FIXME: dsymutil-classic keeps the old abbreviation around
2645 // even if it's not used. We can remove this (and the copyAbbrev
2646 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2647 if (!Copied) {
2648 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2649 Copied = true;
2650 }
2651 continue;
2652 }
2653
Frederic Rissb8b43d52015-03-04 22:07:44 +00002654 DWARFFormValue Val(AttrSpec.Form);
2655 uint32_t AttrSize = Offset;
2656 Val.extractValue(Data, &Offset, &U);
2657 AttrSize = Offset - AttrSize;
2658
Frederic Riss31da3242015-03-11 18:45:52 +00002659 OutOffset +=
2660 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002661 }
2662
Frederic Rissbce93ff2015-03-16 02:05:10 +00002663 // Look for accelerator entries.
2664 uint16_t Tag = InputDIE.getTag();
2665 // FIXME: This is slightly wrong. An inline_subroutine without a
2666 // low_pc, but with AT_ranges might be interesting to get into the
2667 // accelerator tables too. For now stick with dsymutil's behavior.
2668 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2669 Tag != dwarf::DW_TAG_compile_unit &&
2670 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2671 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2672 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2673 AttrInfo.MangledNameOffset,
2674 Tag == dwarf::DW_TAG_inlined_subroutine);
2675 if (AttrInfo.Name)
2676 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2677 Tag == dwarf::DW_TAG_inlined_subroutine);
2678 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2679 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2680 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2681 }
2682
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002683 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002684 // If a scope DIE is kept, we must have kept at least one child. If
2685 // it's not the case, we'll just be emitting one wasteful end of
2686 // children marker, but things won't break.
2687 if (InputDIE.hasChildren())
2688 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2689 // Assign a permanent abbrev number
Adrian Prantl3565af42015-09-14 16:46:10 +00002690 Linker.AssignAbbrev(NewAbbrev);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002691 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002692
2693 // Add the size of the abbreviation number to the output offset.
2694 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2695
2696 if (!Abbrev->hasChildren()) {
2697 // Update our size.
2698 Die->setSize(OutOffset - Die->getOffset());
2699 return Die;
2700 }
2701
2702 // Recursively clone children.
2703 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2704 Child = Child->getSibling()) {
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002705 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset, Flags)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002706 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002707 OutOffset = Clone->getOffset() + Clone->getSize();
2708 }
2709 }
2710
2711 // Account for the end of children marker.
2712 OutOffset += sizeof(int8_t);
2713 // Update our size.
2714 Die->setSize(OutOffset - Die->getOffset());
2715 return Die;
2716}
2717
Frederic Riss25440872015-03-13 23:30:31 +00002718/// \brief Patch the input object file relevant debug_ranges entries
2719/// and emit them in the output file. Update the relevant attributes
2720/// to point at the new entries.
2721void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2722 DWARFContext &OrigDwarf) const {
2723 DWARFDebugRangeList RangeList;
2724 const auto &FunctionRanges = Unit.getFunctionRanges();
2725 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2726 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2727 OrigDwarf.isLittleEndian(), AddressSize);
2728 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2729 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002730 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002731 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2732 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2733 // Ranges addresses are based on the unit's low_pc. Compute the
2734 // offset we need to apply to adapt to the the new unit's low_pc.
2735 int64_t UnitPcOffset = 0;
2736 if (OrigLowPc != -1ULL)
2737 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2738
2739 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002740 uint32_t Offset = RangeAttribute.get();
2741 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002742 RangeList.extract(RangeExtractor, &Offset);
2743 const auto &Entries = RangeList.getEntries();
Frederic Riss94546202015-08-31 05:09:32 +00002744 if (!Entries.empty()) {
2745 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
Frederic Riss25440872015-03-13 23:30:31 +00002746
Frederic Riss25440872015-03-13 23:30:31 +00002747 if (CurrRange == InvalidRange ||
Frederic Riss94546202015-08-31 05:09:32 +00002748 First.StartAddress + OrigLowPc < CurrRange.start() ||
2749 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2750 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2751 if (CurrRange == InvalidRange ||
2752 CurrRange.start() > First.StartAddress + OrigLowPc) {
2753 reportWarning("no mapping for range.");
2754 continue;
2755 }
Frederic Riss25440872015-03-13 23:30:31 +00002756 }
2757 }
2758
2759 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2760 AddressSize);
2761 }
2762}
2763
Frederic Riss563b1b02015-03-14 03:46:51 +00002764/// \brief Generate the debug_aranges entries for \p Unit and if the
2765/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2766/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002767/// FIXME: this could actually be done right in patchRangesForUnit,
2768/// but for the sake of initial bit-for-bit compatibility with legacy
2769/// dsymutil, we have to do it in a delayed pass.
2770void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002771 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002772 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002773 Attr->set(Streamer->getRangesSectionSize());
2774 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002775}
2776
Frederic Riss63786b02015-03-15 20:45:43 +00002777/// \brief Insert the new line info sequence \p Seq into the current
2778/// set of already linked line info \p Rows.
2779static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2780 std::vector<DWARFDebugLine::Row> &Rows) {
2781 if (Seq.empty())
2782 return;
2783
2784 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2785 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2786 Seq.clear();
2787 return;
2788 }
2789
2790 auto InsertPoint = std::lower_bound(
2791 Rows.begin(), Rows.end(), Seq.front(),
2792 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2793 return LHS.Address < RHS.Address;
2794 });
2795
2796 // FIXME: this only removes the unneeded end_sequence if the
2797 // sequences have been inserted in order. using a global sort like
2798 // described in patchLineTableForUnit() and delaying the end_sequene
2799 // elimination to emitLineTableForUnit() we can get rid of all of them.
2800 if (InsertPoint != Rows.end() &&
2801 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2802 *InsertPoint = Seq.front();
2803 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2804 } else {
2805 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2806 }
2807
2808 Seq.clear();
2809}
2810
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002811static void patchStmtList(DIE &Die, DIEInteger Offset) {
2812 for (auto &V : Die.values())
2813 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002814 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002815 return;
2816 }
2817
2818 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2819}
2820
Frederic Riss63786b02015-03-15 20:45:43 +00002821/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2822/// recreate a relocated version of these for the address ranges that
2823/// are present in the binary.
2824void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2825 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002826 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002827 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2828 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2829 if (StmtList == -1ULL)
2830 return;
2831
2832 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002833 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2834 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002835
2836 // Parse the original line info for the unit.
2837 DWARFDebugLine::LineTable LineTable;
2838 uint32_t StmtOffset = StmtList;
2839 StringRef LineData = OrigDwarf.getLineSection().Data;
2840 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2841 Unit.getOrigUnit().getAddressByteSize());
2842 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2843 &StmtOffset);
2844
2845 // This vector is the output line table.
2846 std::vector<DWARFDebugLine::Row> NewRows;
2847 NewRows.reserve(LineTable.Rows.size());
2848
2849 // Current sequence of rows being extracted, before being inserted
2850 // in NewRows.
2851 std::vector<DWARFDebugLine::Row> Seq;
2852 const auto &FunctionRanges = Unit.getFunctionRanges();
2853 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2854
2855 // FIXME: This logic is meant to generate exactly the same output as
2856 // Darwin's classic dsynutil. There is a nicer way to implement this
2857 // by simply putting all the relocated line info in NewRows and simply
2858 // sorting NewRows before passing it to emitLineTableForUnit. This
2859 // should be correct as sequences for a function should stay
2860 // together in the sorted output. There are a few corner cases that
2861 // look suspicious though, and that required to implement the logic
2862 // this way. Revisit that once initial validation is finished.
2863
2864 // Iterate over the object file line info and extract the sequences
2865 // that correspond to linked functions.
2866 for (auto &Row : LineTable.Rows) {
2867 // Check wether we stepped out of the range. The range is
2868 // half-open, but consider accept the end address of the range if
2869 // it is marked as end_sequence in the input (because in that
2870 // case, the relocation offset is accurate and that entry won't
2871 // serve as the start of another function).
2872 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2873 Row.Address > CurrRange.stop() ||
2874 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2875 // We just stepped out of a known range. Insert a end_sequence
2876 // corresponding to the end of the range.
2877 uint64_t StopAddress = CurrRange != InvalidRange
2878 ? CurrRange.stop() + CurrRange.value()
2879 : -1ULL;
2880 CurrRange = FunctionRanges.find(Row.Address);
2881 bool CurrRangeValid =
2882 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2883 if (!CurrRangeValid) {
2884 CurrRange = InvalidRange;
2885 if (StopAddress != -1ULL) {
2886 // Try harder by looking in the DebugMapObject function
2887 // ranges map. There are corner cases where this finds a
2888 // valid entry. It's unclear if this is right or wrong, but
2889 // for now do as dsymutil.
2890 // FIXME: Understand exactly what cases this addresses and
2891 // potentially remove it along with the Ranges map.
2892 auto Range = Ranges.lower_bound(Row.Address);
2893 if (Range != Ranges.begin() && Range != Ranges.end())
2894 --Range;
2895
2896 if (Range != Ranges.end() && Range->first <= Row.Address &&
2897 Range->second.first >= Row.Address) {
2898 StopAddress = Row.Address + Range->second.second;
2899 }
2900 }
2901 }
2902 if (StopAddress != -1ULL && !Seq.empty()) {
2903 // Insert end sequence row with the computed end address, but
2904 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00002905 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00002906 NextLine.Address = StopAddress;
2907 NextLine.EndSequence = 1;
2908 NextLine.PrologueEnd = 0;
2909 NextLine.BasicBlock = 0;
2910 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00002911 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00002912 insertLineSequence(Seq, NewRows);
2913 }
2914
2915 if (!CurrRangeValid)
2916 continue;
2917 }
2918
2919 // Ignore empty sequences.
2920 if (Row.EndSequence && Seq.empty())
2921 continue;
2922
2923 // Relocate row address and add it to the current sequence.
2924 Row.Address += CurrRange.value();
2925 Seq.emplace_back(Row);
2926
2927 if (Row.EndSequence)
2928 insertLineSequence(Seq, NewRows);
2929 }
2930
2931 // Finished extracting, now emit the line tables.
2932 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2933 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2934 // prologue over and that works because we act as both producer and
2935 // consumer. It would be nicer to have a real configurable line
2936 // table emitter.
2937 if (LineTable.Prologue.Version != 2 ||
2938 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00002939 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00002940 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00002941 else {
2942 MCDwarfLineTableParams Params;
2943 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
2944 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
2945 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
2946 Streamer->emitLineTableForUnit(Params,
2947 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00002948 LineTable.Prologue.MinInstLength, NewRows,
2949 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00002950 }
Frederic Riss63786b02015-03-15 20:45:43 +00002951}
2952
Frederic Rissbce93ff2015-03-16 02:05:10 +00002953void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2954 Streamer->emitPubNamesForUnit(Unit);
2955 Streamer->emitPubTypesForUnit(Unit);
2956}
2957
Frederic Riss5a642072015-06-05 23:06:11 +00002958/// \brief Read the frame info stored in the object, and emit the
2959/// patched frame descriptions for the linked binary.
2960///
2961/// This is actually pretty easy as the data of the CIEs and FDEs can
2962/// be considered as black boxes and moved as is. The only thing to do
2963/// is to patch the addresses in the headers.
2964void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2965 DWARFContext &OrigDwarf,
2966 unsigned AddrSize) {
2967 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2968 if (FrameData.empty())
2969 return;
2970
2971 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2972 uint32_t InputOffset = 0;
2973
2974 // Store the data of the CIEs defined in this object, keyed by their
2975 // offsets.
2976 DenseMap<uint32_t, StringRef> LocalCIES;
2977
2978 while (Data.isValidOffset(InputOffset)) {
2979 uint32_t EntryOffset = InputOffset;
2980 uint32_t InitialLength = Data.getU32(&InputOffset);
2981 if (InitialLength == 0xFFFFFFFF)
2982 return reportWarning("Dwarf64 bits no supported");
2983
2984 uint32_t CIEId = Data.getU32(&InputOffset);
2985 if (CIEId == 0xFFFFFFFF) {
2986 // This is a CIE, store it.
2987 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2988 LocalCIES[EntryOffset] = CIEData;
2989 // The -4 is to account for the CIEId we just read.
2990 InputOffset += InitialLength - 4;
2991 continue;
2992 }
2993
2994 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2995
2996 // Some compilers seem to emit frame info that doesn't start at
2997 // the function entry point, thus we can't just lookup the address
2998 // in the debug map. Use the linker's range map to see if the FDE
2999 // describes something that we can relocate.
3000 auto Range = Ranges.upper_bound(Loc);
3001 if (Range != Ranges.begin())
3002 --Range;
3003 if (Range == Ranges.end() || Range->first > Loc ||
3004 Range->second.first <= Loc) {
3005 // The +4 is to account for the size of the InitialLength field itself.
3006 InputOffset = EntryOffset + InitialLength + 4;
3007 continue;
3008 }
3009
3010 // This is an FDE, and we have a mapping.
3011 // Have we already emitted a corresponding CIE?
3012 StringRef CIEData = LocalCIES[CIEId];
3013 if (CIEData.empty())
3014 return reportWarning("Inconsistent debug_frame content. Dropping.");
3015
3016 // Look if we already emitted a CIE that corresponds to the
3017 // referenced one (the CIE data is the key of that lookup).
3018 auto IteratorInserted = EmittedCIEs.insert(
3019 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3020 // If there is no CIE yet for this ID, emit it.
3021 if (IteratorInserted.second ||
3022 // FIXME: dsymutil-classic only caches the last used CIE for
3023 // reuse. Mimic that behavior for now. Just removing that
3024 // second half of the condition and the LastCIEOffset variable
3025 // makes the code DTRT.
3026 LastCIEOffset != IteratorInserted.first->getValue()) {
3027 LastCIEOffset = Streamer->getFrameSectionSize();
3028 IteratorInserted.first->getValue() = LastCIEOffset;
3029 Streamer->emitCIE(CIEData);
3030 }
3031
3032 // Emit the FDE with updated address and CIE pointer.
3033 // (4 + AddrSize) is the size of the CIEId + initial_location
3034 // fields that will get reconstructed by emitFDE().
3035 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3036 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3037 Loc + Range->second.second,
3038 FrameData.substr(InputOffset, FDERemainingBytes));
3039 InputOffset += FDERemainingBytes;
3040 }
3041}
3042
Adrian Prantl3565af42015-09-14 16:46:10 +00003043void DwarfLinker::DIECloner::copyAbbrev(
3044 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
Frederic Riss29eedc72015-09-11 04:17:30 +00003045 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3046 dwarf::Form(Abbrev.hasChildren()));
3047
3048 for (const auto &Attr : Abbrev.attributes()) {
3049 uint16_t Form = Attr.Form;
3050 if (hasODR && isODRAttribute(Attr.Attr))
3051 Form = dwarf::DW_FORM_ref_addr;
3052 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3053 }
3054
Adrian Prantl3565af42015-09-14 16:46:10 +00003055 Linker.AssignAbbrev(Copy);
Frederic Riss29eedc72015-09-11 04:17:30 +00003056}
3057
Frederic Risseb85c8f2015-07-24 06:41:11 +00003058ErrorOr<const object::ObjectFile &>
3059DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3060 const DebugMap &Map) {
3061 auto ErrOrObjs =
3062 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
Frederic Rissafeac302015-08-31 05:16:35 +00003063 if (std::error_code EC = ErrOrObjs.getError()) {
Frederic Risseb85c8f2015-07-24 06:41:11 +00003064 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
Frederic Rissafeac302015-08-31 05:16:35 +00003065 return EC;
3066 }
Frederic Risseb85c8f2015-07-24 06:41:11 +00003067 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3068 if (std::error_code EC = ErrOrObj.getError())
3069 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3070 return ErrOrObj;
3071}
3072
Adrian Prantl3565af42015-09-14 16:46:10 +00003073void DwarfLinker::DIECloner::cloneAllCompileUnits(
3074 DWARFContextInMemory &DwarfContext) {
3075 if (!Linker.Streamer)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003076 return;
3077
3078 for (auto &CurrentUnit : CompileUnits) {
3079 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Adrian Prantl3565af42015-09-14 16:46:10 +00003080 CurrentUnit.setStartOffset(Linker.OutputDebugInfoSize);
Adrian Prantl3abe18d2015-09-14 23:27:26 +00003081 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PC offset */,
3082 11 /* Unit Header size */, 0);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003083 CurrentUnit.setOutputUnitDIE(OutputDIE);
Adrian Prantl3565af42015-09-14 16:46:10 +00003084 Linker.OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3085 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003086 continue;
3087 // FIXME: for compatibility with the classic dsymutil, we emit
3088 // an empty line table for the unit, even if the unit doesn't
3089 // actually exist in the DIE tree.
Adrian Prantl3565af42015-09-14 16:46:10 +00003090 Linker.patchLineTableForUnit(CurrentUnit, DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003091 if (!OutputDIE)
3092 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003093 Linker.patchRangesForUnit(CurrentUnit, DwarfContext);
3094 Linker.Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3095 Linker.emitAcceleratorEntriesForUnit(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003096 }
3097
Adrian Prantl3565af42015-09-14 16:46:10 +00003098 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003099 return;
3100
3101 // Emit all the compile unit's debug information.
3102 for (auto &CurrentUnit : CompileUnits) {
Adrian Prantl3565af42015-09-14 16:46:10 +00003103 Linker.generateUnitRanges(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003104 CurrentUnit.fixupForwardReferences();
Adrian Prantl3565af42015-09-14 16:46:10 +00003105 Linker.Streamer->emitCompileUnitHeader(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003106 if (!CurrentUnit.getOutputUnitDIE())
3107 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003108 Linker.Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003109 }
3110}
3111
Frederic Rissd3455182015-01-28 18:27:01 +00003112bool DwarfLinker::link(const DebugMap &Map) {
3113
Frederic Rissc99ea202015-02-28 00:29:11 +00003114 if (!createStreamer(Map.getTriple(), OutputFilename))
3115 return false;
3116
Frederic Rissb8b43d52015-03-04 22:07:44 +00003117 // Size of the DIEs (and headers) generated for the linked output.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003118 OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003119 // A unique ID that identifies each compile unit.
3120 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00003121 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003122 CurrentDebugObject = Obj.get();
3123
Frederic Rissb9818322015-02-28 00:29:07 +00003124 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003125 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003126 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3127 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003128 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003129
Frederic Riss1036e642015-02-13 23:18:22 +00003130 // Look for relocations that correspond to debug map entries.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003131 RelocationManager RelocMgr(*this);
3132 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003133 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003134 outs() << "No valid relocations found. Skipping.\n";
3135 continue;
3136 }
3137
Frederic Riss563cba62015-01-28 22:15:14 +00003138 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003139 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003140 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003141
Frederic Riss563cba62015-01-28 22:15:14 +00003142 // In a first phase, just read in the debug info and store the DIE
3143 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00003144 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003145 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003146 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003147 outs() << "Input compilation unit:";
3148 CUDie->dump(outs(), CU.get(), 0);
3149 }
Frederic Riss1c650942015-07-21 22:41:43 +00003150 Units.emplace_back(*CU, UnitID++, !Options.NoODR);
3151 gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
3152 StringPool, ODRContexts);
Frederic Rissd3455182015-01-28 18:27:01 +00003153 }
Frederic Riss563cba62015-01-28 22:15:14 +00003154
Frederic Riss84c09a52015-02-13 23:18:34 +00003155 // Then mark all the DIEs that need to be present in the linked
3156 // output and collect some information about them. Note that this
3157 // loop can not be merged with the previous one becaue cross-cu
3158 // references require the ParentIdx to be setup for every CU in
3159 // the object file before calling this.
3160 for (auto &CurrentUnit : Units)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003161 lookForDIEsToKeep(RelocMgr, *CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00003162 CurrentUnit, 0);
3163
Frederic Riss23e20e92015-03-07 01:25:09 +00003164 // The calls to applyValidRelocs inside cloneDIE will walk the
3165 // reloc array again (in the same way findValidRelocsInDebugInfo()
3166 // did). We need to reset the NextValidReloc index to the beginning.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003167 RelocMgr.resetValidRelocs();
3168 if (RelocMgr.hasValidRelocs())
Adrian Prantl3565af42015-09-14 16:46:10 +00003169 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3170 .cloneAllCompileUnits(DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003171 if (!Options.NoOutput && !Units.empty())
Frederic Riss5a642072015-06-05 23:06:11 +00003172 patchFrameInfoForObject(*Obj, DwarfContext,
3173 Units[0].getOrigUnit().getAddressByteSize());
3174
Frederic Riss563cba62015-01-28 22:15:14 +00003175 // Clean-up before starting working on the next object.
3176 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003177 }
3178
Frederic Rissb8b43d52015-03-04 22:07:44 +00003179 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003180 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003181 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003182 Streamer->emitStrings(StringPool);
3183 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003184
Frederic Riss24faade2015-09-02 16:49:13 +00003185 return Options.NoOutput ? true : Streamer->finish(Map);
Frederic Riss231f7142014-12-12 17:31:24 +00003186}
3187}
Frederic Rissd3455182015-01-28 18:27:01 +00003188
Frederic Riss30711fb2015-08-26 05:09:52 +00003189/// \brief Get the offset of string \p S in the string table. This
3190/// can insert a new element or return the offset of a preexisitng
3191/// one.
3192uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3193 if (S.empty() && !Strings.empty())
3194 return 0;
3195
3196 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3197 MapTy::iterator It;
3198 bool Inserted;
3199
3200 // A non-empty string can't be at offset 0, so if we have an entry
3201 // with a 0 offset, it must be a previously interned string.
3202 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3203 if (Inserted || It->getValue().first == 0) {
3204 // Set offset and chain at the end of the entries list.
3205 It->getValue().first = CurrentEndOffset;
3206 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3207 Last->getValue().second = &*It;
3208 Last = &*It;
3209 }
3210 return It->getValue().first;
3211}
3212
3213/// \brief Put \p S into the StringMap so that it gets permanent
3214/// storage, but do not actually link it in the chain of elements
3215/// that go into the output section. A latter call to
3216/// getStringOffset() with the same string will chain it though.
3217StringRef NonRelocatableStringpool::internString(StringRef S) {
3218 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3219 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3220 return InsertResult.first->getKey();
3221}
3222
Frederic Riss65e145c2015-08-26 05:09:55 +00003223void warn(const Twine &Warning, const Twine &Context) {
3224 errs() << Twine("while processing ") + Context + ":\n";
3225 errs() << Twine("warning: ") + Warning + "\n";
3226}
3227
3228bool error(const Twine &Error, const Twine &Context) {
3229 errs() << Twine("while processing ") + Context + ":\n";
3230 errs() << Twine("error: ") + Error + "\n";
3231 return false;
3232}
3233
Frederic Rissb9818322015-02-28 00:29:07 +00003234bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3235 const LinkOptions &Options) {
3236 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003237 return Linker.link(DM);
3238}
3239}
Frederic Riss231f7142014-12-12 17:31:24 +00003240}