blob: c877264a067f7adbd8a1d57e67cf662f3cdcb249 [file] [log] [blame]
Frederic Riss231f7142014-12-12 17:31:24 +00001//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "DebugMap.h"
Frederic Rissd3455182015-01-28 18:27:01 +000010#include "BinaryHolder.h"
11#include "DebugMap.h"
Frederic Riss231f7142014-12-12 17:31:24 +000012#include "dsymutil.h"
Frederic Riss24faade2015-09-02 16:49:13 +000013#include "MachOUtils.h"
Frederic Riss30711fb2015-08-26 05:09:52 +000014#include "NonRelocatableStringpool.h"
Frederic Riss1af75f72015-03-12 18:45:10 +000015#include "llvm/ADT/IntervalMap.h"
Adrian Prantl20937022015-09-23 17:11:10 +000016#include "llvm/ADT/StringMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000017#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000018#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000019#include "llvm/CodeGen/DIE.h"
Frederic Riss1c650942015-07-21 22:41:43 +000020#include "llvm/Config/config.h"
Zachary Turner82af9432015-01-30 18:07:45 +000021#include "llvm/DebugInfo/DWARF/DWARFContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000023#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000024#include "llvm/MC/MCAsmBackend.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000028#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000029#include "llvm/MC/MCInstrInfo.h"
30#include "llvm/MC/MCObjectFileInfo.h"
31#include "llvm/MC/MCRegisterInfo.h"
32#include "llvm/MC/MCStreamer.h"
Pete Cooper81902a32015-05-15 22:19:42 +000033#include "llvm/MC/MCSubtargetInfo.h"
Frederic Riss1036e642015-02-13 23:18:22 +000034#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000035#include "llvm/Support/Dwarf.h"
36#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000037#include "llvm/Support/TargetRegistry.h"
38#include "llvm/Target/TargetMachine.h"
39#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000040#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000041#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000042
43namespace llvm {
44namespace dsymutil {
45
Frederic Rissd3455182015-01-28 18:27:01 +000046namespace {
47
Frederic Riss1af75f72015-03-12 18:45:10 +000048template <typename KeyT, typename ValT>
49using HalfOpenIntervalMap =
50 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
51 IntervalMapHalfOpenInfo<KeyT>>;
52
Frederic Riss25440872015-03-13 23:30:31 +000053typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
54
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000055// FIXME: Delete this structure.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000056struct PatchLocation {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000057 DIE::value_iterator I;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000058
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000059 PatchLocation() = default;
60 PatchLocation(DIE::value_iterator I) : I(I) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000061
62 void set(uint64_t New) const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000063 assert(I);
64 const auto &Old = *I;
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000065 assert(Old.getType() == DIEValue::isInteger);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000066 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000067 }
68
69 uint64_t get() const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000070 assert(I);
71 return I->getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000072 }
73};
74
Frederic Riss1c650942015-07-21 22:41:43 +000075class CompileUnit;
76struct DeclMapInfo;
Frederic Riss1c650942015-07-21 22:41:43 +000077
78/// A DeclContext is a named program scope that is used for ODR
79/// uniquing of types.
80/// The set of DeclContext for the ODR-subject parts of a Dwarf link
81/// is expanded (and uniqued) with each new object file processed. We
82/// need to determine the context of each DIE in an linked object file
83/// to see if the corresponding type has already been emitted.
84///
85/// The contexts are conceptually organised as a tree (eg. a function
86/// scope is contained in a namespace scope that contains other
87/// scopes), but storing/accessing them in an actual tree is too
88/// inefficient: we need to be able to very quickly query a context
89/// for a given child context by name. Storing a StringMap in each
90/// DeclContext would be too space inefficient.
91/// The solution here is to give each DeclContext a link to its parent
92/// (this allows to walk up the tree), but to query the existance of a
93/// specific DeclContext using a separate DenseMap keyed on the hash
94/// of the fully qualified name of the context.
95class DeclContext {
96 unsigned QualifiedNameHash;
97 uint32_t Line;
98 uint32_t ByteSize;
99 uint16_t Tag;
100 StringRef Name;
101 StringRef File;
102 const DeclContext &Parent;
103 const DWARFDebugInfoEntryMinimal *LastSeenDIE;
104 uint32_t LastSeenCompileUnitID;
105 uint32_t CanonicalDIEOffset;
106
107 friend DeclMapInfo;
108
109public:
110 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
111
112 DeclContext()
113 : QualifiedNameHash(0), Line(0), ByteSize(0),
114 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
115 LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
116
117 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
118 StringRef Name, StringRef File, const DeclContext &Parent,
119 const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
120 unsigned CUId = 0)
121 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
122 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
123 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
124
125 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
126
127 bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
128
129 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
130 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
131
132 uint16_t getTag() const { return Tag; }
133 StringRef getName() const { return Name; }
134};
135
136/// Info type for the DenseMap storing the DeclContext pointers.
137struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
138 using DenseMapInfo<DeclContext *>::getEmptyKey;
139 using DenseMapInfo<DeclContext *>::getTombstoneKey;
140
141 static unsigned getHashValue(const DeclContext *Ctxt) {
142 return Ctxt->QualifiedNameHash;
143 }
144
145 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
146 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
147 return RHS == LHS;
148 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
149 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
150 LHS->Name.data() == RHS->Name.data() &&
151 LHS->File.data() == RHS->File.data() &&
152 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
153 }
154};
155
156/// This class gives a tree-like API to the DenseMap that stores the
157/// DeclContext objects. It also holds the BumpPtrAllocator where
158/// these objects will be allocated.
159class DeclContextTree {
160 BumpPtrAllocator Allocator;
161 DeclContext Root;
162 DeclContext::Map Contexts;
163
164public:
165 /// Get the child of \a Context described by \a DIE in \a Unit. The
166 /// required strings will be interned in \a StringPool.
167 /// \returns The child DeclContext along with one bit that is set if
168 /// this context is invalid.
Adrian Prantl42562c32015-10-02 00:27:08 +0000169 /// An invalid context means it shouldn't be considered for uniquing, but its
170 /// not returning null, because some children of that context might be
171 /// uniquing candidates. FIXME: The invalid bit along the return value is to
172 /// emulate some dsymutil-classic functionality.
Frederic Riss1c650942015-07-21 22:41:43 +0000173 PointerIntPair<DeclContext *, 1>
174 getChildDeclContext(DeclContext &Context,
175 const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
Adrian Prantl42562c32015-10-02 00:27:08 +0000176 NonRelocatableStringpool &StringPool, bool InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +0000177
178 DeclContext &getRoot() { return Root; }
179};
180
Frederic Riss563cba62015-01-28 22:15:14 +0000181/// \brief Stores all information relating to a compile unit, be it in
182/// its original instance in the object file to its brand new cloned
183/// and linked DIE tree.
184class CompileUnit {
185public:
186 /// \brief Information gathered about a DIE in the object file.
187 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +0000188 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss1c650942015-07-21 22:41:43 +0000189 DeclContext *Ctxt; ///< ODR Declaration context.
Frederic Riss9833de62015-03-06 23:22:53 +0000190 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +0000191 uint32_t ParentIdx; ///< The index of this DIE's parent.
Adrian Prantla112ef92015-09-23 17:35:52 +0000192 bool Keep : 1; ///< Is the DIE part of the linked output?
193 bool InDebugMap : 1;///< Was this DIE's entity found in the map?
194 bool Prune : 1; ///< Is this a pure forward declaration we can strip?
Frederic Riss563cba62015-01-28 22:15:14 +0000195 };
196
Adrian Prantla112ef92015-09-23 17:35:52 +0000197 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR,
198 StringRef ClangModuleName)
Frederic Riss3cced052015-03-14 03:46:40 +0000199 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Adrian Prantla112ef92015-09-23 17:35:52 +0000200 Ranges(RangeAlloc), ClangModuleName(ClangModuleName) {
Frederic Riss563cba62015-01-28 22:15:14 +0000201 Info.resize(OrigUnit.getNumDIEs());
Frederic Riss1c650942015-07-21 22:41:43 +0000202
203 const auto *CUDie = OrigUnit.getUnitDIE(false);
204 unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
205 &OrigUnit, dwarf::DW_AT_language, 0);
206 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
207 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
208 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
209 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
210 Lang == dwarf::DW_LANG_ObjC_plus_plus);
Frederic Riss563cba62015-01-28 22:15:14 +0000211 }
212
Frederic Riss2838f9e2015-03-05 05:29:05 +0000213 CompileUnit(CompileUnit &&RHS)
214 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
215 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000216 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
217 // The CompileUnit container has been 'reserve()'d with the right
218 // size. We cannot move the IntervalMap anyway.
219 llvm_unreachable("CompileUnits should not be moved.");
220 }
David Blaikiea8adc132015-03-04 22:20:52 +0000221
Frederic Rissc3349d42015-02-13 23:18:27 +0000222 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000223
Frederic Riss3cced052015-03-14 03:46:40 +0000224 unsigned getUniqueID() const { return ID; }
225
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +0000226 DIE *getOutputUnitDIE() const { return CUDie; }
227 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000228
Frederic Riss1c650942015-07-21 22:41:43 +0000229 bool hasODR() const { return HasODR; }
Adrian Prantla112ef92015-09-23 17:35:52 +0000230 bool isClangModule() const { return !ClangModuleName.empty(); }
231 const std::string &getClangModuleName() const { return ClangModuleName; }
Frederic Riss1c650942015-07-21 22:41:43 +0000232
Frederic Riss563cba62015-01-28 22:15:14 +0000233 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
234 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
235
Frederic Rissb8b43d52015-03-04 22:07:44 +0000236 uint64_t getStartOffset() const { return StartOffset; }
237 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000238 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000239
Frederic Riss5a62dc32015-03-13 18:35:54 +0000240 uint64_t getLowPc() const { return LowPc; }
241 uint64_t getHighPc() const { return HighPc; }
242
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000243 Optional<PatchLocation> getUnitRangesAttribute() const {
244 return UnitRangeAttribute;
245 }
Frederic Riss25440872015-03-13 23:30:31 +0000246 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000247 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000248 return RangeAttributes;
249 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000250
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000251 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000252 getLocationAttributes() const {
253 return LocationAttributes;
254 }
255
Adrian Prantle5162db2015-09-22 22:20:50 +0000256 void setHasInterestingContent() { HasInterestingContent = true; }
257 bool hasInterestingContent() { return HasInterestingContent; }
258
259 /// Mark every DIE in this unit as kept. This function also
260 /// marks variables as InDebugMap so that they appear in the
261 /// reconstructed accelerator tables.
262 void markEverythingAsKept();
263
Frederic Riss9d441b62015-03-06 23:22:50 +0000264 /// \brief Compute the end offset for this unit. Must be
265 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000266 /// \returns the next unit offset (which is also the current
267 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000268 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000269
Frederic Riss6afcfce2015-03-13 18:35:57 +0000270 /// \brief Keep track of a forward reference to DIE \p Die in \p
271 /// RefUnit by \p Attr. The attribute should be fixed up later to
Frederic Riss1c650942015-07-21 22:41:43 +0000272 /// point to the absolute offset of \p Die in the debug_info section
273 /// or to the canonical offset of \p Ctxt if it is non-null.
Frederic Riss6afcfce2015-03-13 18:35:57 +0000274 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000275 DeclContext *Ctxt, PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000276
277 /// \brief Apply all fixups recored by noteForwardReference().
278 void fixupForwardReferences();
279
Frederic Riss1af75f72015-03-12 18:45:10 +0000280 /// \brief Add a function range [\p LowPC, \p HighPC) that is
281 /// relocatad by applying offset \p PCOffset.
282 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
283
Frederic Riss5c9c7062015-03-13 23:55:29 +0000284 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000285 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000286 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000287
Frederic Rissdfb97902015-03-14 15:49:07 +0000288 /// \brief Keep track of a location attribute pointing to a location
289 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000290 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000291
Frederic Rissbce93ff2015-03-16 02:05:10 +0000292 /// \brief Add a name accelerator entry for \p Die with \p Name
293 /// which is stored in the string table at \p Offset.
294 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
295 bool SkipPubnamesSection = false);
296
297 /// \brief Add a type accelerator entry for \p Die with \p Name
298 /// which is stored in the string table at \p Offset.
299 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
300
301 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000302 StringRef Name; ///< Name of the entry.
303 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000304 uint32_t NameOffset; ///< Offset of Name in the string pool.
305 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
306
307 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
308 bool SkipPubSection = false)
309 : Name(Name), Die(Die), NameOffset(NameOffset),
310 SkipPubSection(SkipPubSection) {}
311 };
312
313 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
314 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
315
Frederic Riss1c650942015-07-21 22:41:43 +0000316 /// Get the full path for file \a FileNum in the line table
317 const char *getResolvedPath(unsigned FileNum) {
318 if (FileNum >= ResolvedPaths.size())
319 return nullptr;
320 return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
321 : nullptr;
322 }
323
324 /// Set the fully resolved path for the line-table's file \a FileNum
325 /// to \a Path.
326 void setResolvedPath(unsigned FileNum, const std::string &Path) {
327 if (ResolvedPaths.size() <= FileNum)
328 ResolvedPaths.resize(FileNum + 1);
329 ResolvedPaths[FileNum] = Path;
330 }
331
Frederic Riss563cba62015-01-28 22:15:14 +0000332private:
333 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000334 unsigned ID;
Frederic Riss1c650942015-07-21 22:41:43 +0000335 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
336 DIE *CUDie; ///< Root of the linked DIE tree.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000337
338 uint64_t StartOffset;
339 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000340
Frederic Riss5a62dc32015-03-13 18:35:54 +0000341 uint64_t LowPc;
342 uint64_t HighPc;
343
Frederic Riss9833de62015-03-06 23:22:53 +0000344 /// \brief A list of attributes to fixup with the absolute offset of
345 /// a DIE in the debug_info section.
346 ///
347 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000348 /// cloning because for cross-cu forward refences the target DIE's
349 /// offset isn't known you emit the reference attribute.
Frederic Riss1c650942015-07-21 22:41:43 +0000350 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
351 PatchLocation>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000352
Frederic Riss25440872015-03-13 23:30:31 +0000353 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000354 /// \brief The ranges in that interval map are the PC ranges for
355 /// functions in this unit, associated with the PC offset to apply
356 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000357 FunctionIntervals Ranges;
358
359 /// \brief DW_AT_ranges attributes to patch after we have gathered
360 /// all the unit's function addresses.
361 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000362 std::vector<PatchLocation> RangeAttributes;
363 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000364 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000365
366 /// \brief Location attributes that need to be transfered from th
367 /// original debug_loc section to the liked one. They are stored
368 /// along with the PC offset that is to be applied to their
369 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000370 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000371
372 /// \brief Accelerator entries for the unit, both for the pub*
373 /// sections and the apple* ones.
374 /// @{
375 std::vector<AccelInfo> Pubnames;
376 std::vector<AccelInfo> Pubtypes;
377 /// @}
Frederic Riss1c650942015-07-21 22:41:43 +0000378
379 /// Cached resolved paths from the line table.
380 std::vector<std::string> ResolvedPaths;
381
382 /// Is this unit subject to the ODR rule?
383 bool HasODR;
Adrian Prantle5162db2015-09-22 22:20:50 +0000384 /// Did a DIE actually contain a valid reloc?
385 bool HasInterestingContent;
Adrian Prantla112ef92015-09-23 17:35:52 +0000386 /// If this is a Clang module, this holds the module's name.
387 std::string ClangModuleName;
Frederic Riss563cba62015-01-28 22:15:14 +0000388};
389
Adrian Prantle5162db2015-09-22 22:20:50 +0000390void CompileUnit::markEverythingAsKept() {
391 for (auto &I : Info)
Adrian Prantla112ef92015-09-23 17:35:52 +0000392 // Mark everything that wasn't explicity marked for pruning.
393 I.Keep = !I.Prune;
Adrian Prantle5162db2015-09-22 22:20:50 +0000394}
395
Frederic Riss9d441b62015-03-06 23:22:50 +0000396uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000397 NextUnitOffset = StartOffset + 11 /* Header size */;
398 // The root DIE might be null, meaning that the Unit had nothing to
399 // contribute to the linked output. In that case, we will emit the
400 // unit header without any actual DIE.
401 if (CUDie)
402 NextUnitOffset += CUDie->getSize();
403 return NextUnitOffset;
404}
405
Frederic Riss6afcfce2015-03-13 18:35:57 +0000406/// \brief Keep track of a forward cross-cu reference from this unit
407/// to \p Die that lives in \p RefUnit.
408void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000409 DeclContext *Ctxt, PatchLocation Attr) {
410 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000411}
412
413/// \brief Apply all fixups recorded by noteForwardReference().
414void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000415 for (const auto &Ref : ForwardDIEReferences) {
416 DIE *RefDie;
417 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000418 PatchLocation Attr;
Frederic Riss1c650942015-07-21 22:41:43 +0000419 DeclContext *Ctxt;
420 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
421 if (Ctxt && Ctxt->getCanonicalDIEOffset())
422 Attr.set(Ctxt->getCanonicalDIEOffset());
423 else
424 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000425 }
Frederic Riss9833de62015-03-06 23:22:53 +0000426}
427
Frederic Riss5a62dc32015-03-13 18:35:54 +0000428void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
429 int64_t PcOffset) {
430 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
431 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
432 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000433}
434
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000435void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000436 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
437 RangeAttributes.push_back(Attr);
438 else
439 UnitRangeAttribute = Attr;
440}
441
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000442void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000443 LocationAttributes.emplace_back(Attr, PcOffset);
444}
445
Frederic Rissbce93ff2015-03-16 02:05:10 +0000446/// \brief Add a name accelerator entry for \p Die with \p Name
447/// which is stored in the string table at \p Offset.
448void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
449 uint32_t Offset, bool SkipPubSection) {
450 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
451}
452
453/// \brief Add a type accelerator entry for \p Die with \p Name
454/// which is stored in the string table at \p Offset.
455void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
456 uint32_t Offset) {
457 Pubtypes.emplace_back(Name, Die, Offset, false);
458}
459
Frederic Rissc99ea202015-02-28 00:29:11 +0000460/// \brief The Dwarf streaming logic
461///
462/// All interactions with the MC layer that is used to build the debug
463/// information binary representation are handled in this class.
464class DwarfStreamer {
465 /// \defgroup MCObjects MC layer objects constructed by the streamer
466 /// @{
467 std::unique_ptr<MCRegisterInfo> MRI;
468 std::unique_ptr<MCAsmInfo> MAI;
469 std::unique_ptr<MCObjectFileInfo> MOFI;
470 std::unique_ptr<MCContext> MC;
471 MCAsmBackend *MAB; // Owned by MCStreamer
472 std::unique_ptr<MCInstrInfo> MII;
473 std::unique_ptr<MCSubtargetInfo> MSTI;
474 MCCodeEmitter *MCE; // Owned by MCStreamer
475 MCStreamer *MS; // Owned by AsmPrinter
476 std::unique_ptr<TargetMachine> TM;
477 std::unique_ptr<AsmPrinter> Asm;
478 /// @}
479
480 /// \brief the file we stream the linked Dwarf to.
481 std::unique_ptr<raw_fd_ostream> OutFile;
482
Frederic Riss25440872015-03-13 23:30:31 +0000483 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000484 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000485 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000486 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000487
Frederic Rissbce93ff2015-03-16 02:05:10 +0000488 /// \brief Emit the pubnames or pubtypes section contribution for \p
489 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000490 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000491 const CompileUnit &Unit,
492 const std::vector<CompileUnit::AccelInfo> &Names);
493
Frederic Rissc99ea202015-02-28 00:29:11 +0000494public:
495 /// \brief Actually create the streamer and the ouptut file.
496 ///
497 /// This could be done directly in the constructor, but it feels
498 /// more natural to handle errors through return value.
499 bool init(Triple TheTriple, StringRef OutputFilename);
500
Frederic Rissb8b43d52015-03-04 22:07:44 +0000501 /// \brief Dump the file to the disk.
Frederic Riss24faade2015-09-02 16:49:13 +0000502 bool finish(const DebugMap &);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000503
504 AsmPrinter &getAsmPrinter() const { return *Asm; }
505
506 /// \brief Set the current output section to debug_info and change
507 /// the MC Dwarf version to \p DwarfVersion.
508 void switchToDebugInfoSection(unsigned DwarfVersion);
509
510 /// \brief Emit the compilation unit header for \p Unit in the
511 /// debug_info section.
512 ///
513 /// As a side effect, this also switches the current Dwarf version
514 /// of the MC layer to the one of U.getOrigUnit().
515 void emitCompileUnitHeader(CompileUnit &Unit);
516
517 /// \brief Recursively emit the DIE tree rooted at \p Die.
518 void emitDIE(DIE &Die);
519
520 /// \brief Emit the abbreviation table \p Abbrevs to the
521 /// debug_abbrev section.
522 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000523
524 /// \brief Emit the string table described by \p Pool.
525 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000526
527 /// \brief Emit debug_ranges for \p FuncRange by translating the
528 /// original \p Entries.
529 void emitRangesEntries(
530 int64_t UnitPcOffset, uint64_t OrigLowPc,
531 FunctionIntervals::const_iterator FuncRange,
532 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
533 unsigned AddressSize);
534
Frederic Riss563b1b02015-03-14 03:46:51 +0000535 /// \brief Emit debug_aranges entries for \p Unit and if \p
536 /// DoRangesSection is true, also emit the debug_ranges entries for
537 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
538 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000539
540 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000541
542 /// \brief Emit the debug_loc contribution for \p Unit by copying
543 /// the entries from \p Dwarf and offseting them. Update the
544 /// location attributes to point to the new entries.
545 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000546
547 /// \brief Emit the line table described in \p Rows into the
548 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000549 void emitLineTableForUnit(MCDwarfLineTableParams Params,
550 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000551 std::vector<DWARFDebugLine::Row> &Rows,
552 unsigned AdddressSize);
553
554 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000555
556 /// \brief Emit the .debug_pubnames contribution for \p Unit.
557 void emitPubNamesForUnit(const CompileUnit &Unit);
558
559 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
560 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000561
562 /// \brief Emit a CIE.
563 void emitCIE(StringRef CIEBytes);
564
565 /// \brief Emit an FDE with data \p Bytes.
566 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
567 StringRef Bytes);
568
569 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000570};
571
572bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
573 std::string ErrorStr;
574 std::string TripleName;
575 StringRef Context = "dwarf streamer init";
576
577 // Get the target.
578 const Target *TheTarget =
579 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
580 if (!TheTarget)
581 return error(ErrorStr, Context);
582 TripleName = TheTriple.getTriple();
583
584 // Create all the MC Objects.
585 MRI.reset(TheTarget->createMCRegInfo(TripleName));
586 if (!MRI)
587 return error(Twine("no register info for target ") + TripleName, Context);
588
589 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
590 if (!MAI)
591 return error("no asm info for target " + TripleName, Context);
592
593 MOFI.reset(new MCObjectFileInfo);
594 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000595 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
Frederic Rissc99ea202015-02-28 00:29:11 +0000596 *MC);
597
598 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
599 if (!MAB)
600 return error("no asm backend for target " + TripleName, Context);
601
602 MII.reset(TheTarget->createMCInstrInfo());
603 if (!MII)
604 return error("no instr info info for target " + TripleName, Context);
605
606 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
607 if (!MSTI)
608 return error("no subtarget info for target " + TripleName, Context);
609
Eric Christopher0169e422015-03-10 22:03:14 +0000610 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000611 if (!MCE)
612 return error("no code emitter for target " + TripleName, Context);
613
614 // Create the output file.
615 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000616 OutFile =
617 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000618 if (EC)
619 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
620
Daniel Sanders50f17232015-09-15 16:17:27 +0000621 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
622 *MSTI, false,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000623 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000624 if (!MS)
625 return error("no object streamer for target " + TripleName, Context);
626
627 // Finally create the AsmPrinter we'll use to emit the DIEs.
628 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
629 if (!TM)
630 return error("no target machine for target " + TripleName, Context);
631
632 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
633 if (!Asm)
634 return error("no asm printer for target " + TripleName, Context);
635
Frederic Riss25440872015-03-13 23:30:31 +0000636 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000637 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000638 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000639 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000640
Frederic Rissc99ea202015-02-28 00:29:11 +0000641 return true;
642}
643
Frederic Riss24faade2015-09-02 16:49:13 +0000644bool DwarfStreamer::finish(const DebugMap &DM) {
645 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
646 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
647
Frederic Rissc99ea202015-02-28 00:29:11 +0000648 MS->Finish();
649 return true;
650}
651
Frederic Rissb8b43d52015-03-04 22:07:44 +0000652/// \brief Set the current output section to debug_info and change
653/// the MC Dwarf version to \p DwarfVersion.
654void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
655 MS->SwitchSection(MOFI->getDwarfInfoSection());
656 MC->setDwarfVersion(DwarfVersion);
657}
658
659/// \brief Emit the compilation unit header for \p Unit in the
660/// debug_info section.
661///
662/// A Dwarf scetion header is encoded as:
663/// uint32_t Unit length (omiting this field)
664/// uint16_t Version
665/// uint32_t Abbreviation table offset
666/// uint8_t Address size
667///
668/// Leading to a total of 11 bytes.
669void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
670 unsigned Version = Unit.getOrigUnit().getVersion();
671 switchToDebugInfoSection(Version);
672
673 // Emit size of content not including length itself. The size has
674 // already been computed in CompileUnit::computeOffsets(). Substract
675 // 4 to that size to account for the length field.
676 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
677 Asm->EmitInt16(Version);
678 // We share one abbreviations table across all units so it's always at the
679 // start of the section.
680 Asm->EmitInt32(0);
681 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
682}
683
684/// \brief Emit the \p Abbrevs array as the shared abbreviation table
685/// for the linked Dwarf file.
686void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
687 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
688 Asm->emitDwarfAbbrevs(Abbrevs);
689}
690
691/// \brief Recursively emit the DIE tree rooted at \p Die.
692void DwarfStreamer::emitDIE(DIE &Die) {
693 MS->SwitchSection(MOFI->getDwarfInfoSection());
694 Asm->emitDwarfDIE(Die);
695}
696
Frederic Rissef648462015-03-06 17:56:30 +0000697/// \brief Emit the debug_str section stored in \p Pool.
698void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000699 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000700 for (auto *Entry = Pool.getFirstEntry(); Entry;
701 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000702 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000703 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
704}
705
Frederic Riss25440872015-03-13 23:30:31 +0000706/// \brief Emit the debug_range section contents for \p FuncRange by
707/// translating the original \p Entries. The debug_range section
708/// format is totally trivial, consisting just of pairs of address
709/// sized addresses describing the ranges.
710void DwarfStreamer::emitRangesEntries(
711 int64_t UnitPcOffset, uint64_t OrigLowPc,
712 FunctionIntervals::const_iterator FuncRange,
713 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
714 unsigned AddressSize) {
715 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
716
717 // Offset each range by the right amount.
Frederic Riss94546202015-08-31 05:09:32 +0000718 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
Frederic Riss25440872015-03-13 23:30:31 +0000719 for (const auto &Range : Entries) {
720 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
721 warn("unsupported base address selection operation",
722 "emitting debug_ranges");
723 break;
724 }
725 // Do not emit empty ranges.
726 if (Range.StartAddress == Range.EndAddress)
727 continue;
728
729 // All range entries should lie in the function range.
730 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
731 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
732 warn("inconsistent range data.", "emitting debug_ranges");
733 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
734 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
735 RangesSectionSize += 2 * AddressSize;
736 }
737
738 // Add the terminator entry.
739 MS->EmitIntValue(0, AddressSize);
740 MS->EmitIntValue(0, AddressSize);
741 RangesSectionSize += 2 * AddressSize;
742}
743
Frederic Riss563b1b02015-03-14 03:46:51 +0000744/// \brief Emit the debug_aranges contribution of a unit and
745/// if \p DoDebugRanges is true the debug_range contents for a
746/// compile_unit level DW_AT_ranges attribute (Which are basically the
747/// same thing with a different base address).
748/// Just aggregate all the ranges gathered inside that unit.
749void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
750 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000751 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
752 // Gather the ranges in a vector, so that we can simplify them. The
753 // IntervalMap will have coalesced the non-linked ranges, but here
754 // we want to coalesce the linked addresses.
755 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
756 const auto &FunctionRanges = Unit.getFunctionRanges();
757 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
758 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000759 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
760 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000761
762 // The object addresses where sorted, but again, the linked
763 // addresses might end up in a different order.
764 std::sort(Ranges.begin(), Ranges.end());
765
Frederic Riss563b1b02015-03-14 03:46:51 +0000766 if (!Ranges.empty()) {
767 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
768
Rafael Espindola9ab09232015-03-17 20:07:06 +0000769 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
770 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000771
772 unsigned HeaderSize =
773 sizeof(int32_t) + // Size of contents (w/o this field
774 sizeof(int16_t) + // DWARF ARange version number
775 sizeof(int32_t) + // Offset of CU in the .debug_info section
776 sizeof(int8_t) + // Pointer Size (in bytes)
777 sizeof(int8_t); // Segment Size (in bytes)
778
779 unsigned TupleSize = AddressSize * 2;
780 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
781
782 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000783 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000784 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
785 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
786 Asm->EmitInt8(AddressSize); // Address size
787 Asm->EmitInt8(0); // Segment size
788
Lang Hames9ff69c82015-04-24 19:11:51 +0000789 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000790
791 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
792 ++Range) {
793 uint64_t RangeStart = Range->first;
794 MS->EmitIntValue(RangeStart, AddressSize);
795 while ((Range + 1) != End && Range->second == (Range + 1)->first)
796 ++Range;
797 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
798 }
799
800 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000801 Asm->OutStreamer->EmitIntValue(0, AddressSize);
802 Asm->OutStreamer->EmitIntValue(0, AddressSize);
803 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000804 }
805
806 if (!DoDebugRanges)
807 return;
808
809 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
810 // Offset each range by the right amount.
811 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000812 // Emit coalesced ranges.
813 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000814 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000815 while (Range + 1 != End && Range->second == (Range + 1)->first)
816 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000817 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000818 RangesSectionSize += 2 * AddressSize;
819 }
820
821 // Add the terminator entry.
822 MS->EmitIntValue(0, AddressSize);
823 MS->EmitIntValue(0, AddressSize);
824 RangesSectionSize += 2 * AddressSize;
825}
826
Frederic Rissdfb97902015-03-14 15:49:07 +0000827/// \brief Emit location lists for \p Unit and update attribtues to
828/// point to the new entries.
829void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
830 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000831 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000832
833 if (Attributes.empty())
834 return;
835
836 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
837
838 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
839 const DWARFSection &InputSec = Dwarf.getLocSection();
840 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
841 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000842 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000843 int64_t UnitPcOffset = 0;
844 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
845 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
846 if (OrigLowPc != -1ULL)
847 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
848
849 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000850 uint32_t Offset = Attr.first.get();
851 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000852 // This is the quantity to add to the old location address to get
853 // the correct address for the new one.
854 int64_t LocPcOffset = Attr.second + UnitPcOffset;
855 while (Data.isValidOffset(Offset)) {
856 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
857 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
858 LocSectionSize += 2 * AddressSize;
859 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000860 Asm->OutStreamer->EmitIntValue(0, AddressSize);
861 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000862 break;
863 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000864 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
865 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000866 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000867 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000868 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000869 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000870 StringRef(InputSec.Data.substr(Offset, Length)));
871 Offset += Length;
872 LocSectionSize += Length + 2;
873 }
874 }
875}
876
Frederic Rissa5e14532015-08-07 15:14:13 +0000877void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
878 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000879 unsigned MinInstLength,
880 std::vector<DWARFDebugLine::Row> &Rows,
881 unsigned PointerSize) {
882 // Switch to the section where the table will be emitted into.
883 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000884 MCSymbol *LineStartSym = MC->createTempSymbol();
885 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000886
887 // The first 4 bytes is the total length of the information for this
888 // compilation unit (not including these 4 bytes for the length).
889 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000890 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000891 // Copy Prologue.
892 MS->EmitBytes(PrologueBytes);
893 LineSectionSize += PrologueBytes.size() + 4;
894
Frederic Rissc3820d02015-03-15 22:20:28 +0000895 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000896 raw_svector_ostream EncodingOS(EncodingBuffer);
897
898 if (Rows.empty()) {
899 // We only have the dummy entry, dsymutil emits an entry with a 0
900 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000901 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000902 MS->EmitBytes(EncodingOS.str());
903 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000904 MS->EmitLabel(LineEndSym);
905 return;
906 }
907
908 // Line table state machine fields
909 unsigned FileNum = 1;
910 unsigned LastLine = 1;
911 unsigned Column = 0;
912 unsigned IsStatement = 1;
913 unsigned Isa = 0;
914 uint64_t Address = -1ULL;
915
916 unsigned RowsSinceLastSequence = 0;
917
918 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
919 auto &Row = Rows[Idx];
920
921 int64_t AddressDelta;
922 if (Address == -1ULL) {
923 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
924 MS->EmitULEB128IntValue(PointerSize + 1);
925 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
926 MS->EmitIntValue(Row.Address, PointerSize);
927 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
928 AddressDelta = 0;
929 } else {
930 AddressDelta = (Row.Address - Address) / MinInstLength;
931 }
932
933 // FIXME: code copied and transfromed from
934 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
935 // this code, but the current compatibility requirement with
936 // classic dsymutil makes it hard. Revisit that once this
937 // requirement is dropped.
938
939 if (FileNum != Row.File) {
940 FileNum = Row.File;
941 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
942 MS->EmitULEB128IntValue(FileNum);
943 LineSectionSize += 1 + getULEB128Size(FileNum);
944 }
945 if (Column != Row.Column) {
946 Column = Row.Column;
947 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
948 MS->EmitULEB128IntValue(Column);
949 LineSectionSize += 1 + getULEB128Size(Column);
950 }
951
952 // FIXME: We should handle the discriminator here, but dsymutil
953 // doesn' consider it, thus ignore it for now.
954
955 if (Isa != Row.Isa) {
956 Isa = Row.Isa;
957 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
958 MS->EmitULEB128IntValue(Isa);
959 LineSectionSize += 1 + getULEB128Size(Isa);
960 }
961 if (IsStatement != Row.IsStmt) {
962 IsStatement = Row.IsStmt;
963 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
964 LineSectionSize += 1;
965 }
966 if (Row.BasicBlock) {
967 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
968 LineSectionSize += 1;
969 }
970
971 if (Row.PrologueEnd) {
972 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
973 LineSectionSize += 1;
974 }
975
976 if (Row.EpilogueBegin) {
977 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
978 LineSectionSize += 1;
979 }
980
981 int64_t LineDelta = int64_t(Row.Line) - LastLine;
982 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000983 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000984 MS->EmitBytes(EncodingOS.str());
985 LineSectionSize += EncodingBuffer.size();
986 EncodingBuffer.resize(0);
987 Address = Row.Address;
988 LastLine = Row.Line;
989 RowsSinceLastSequence++;
990 } else {
991 if (LineDelta) {
992 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
993 MS->EmitSLEB128IntValue(LineDelta);
994 LineSectionSize += 1 + getSLEB128Size(LineDelta);
995 }
996 if (AddressDelta) {
997 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
998 MS->EmitULEB128IntValue(AddressDelta);
999 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1000 }
Frederic Rissa5e14532015-08-07 15:14:13 +00001001 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001002 MS->EmitBytes(EncodingOS.str());
1003 LineSectionSize += EncodingBuffer.size();
1004 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +00001005 Address = -1ULL;
1006 LastLine = FileNum = IsStatement = 1;
1007 RowsSinceLastSequence = Column = Isa = 0;
1008 }
1009 }
1010
1011 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +00001012 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001013 MS->EmitBytes(EncodingOS.str());
1014 LineSectionSize += EncodingBuffer.size();
1015 EncodingBuffer.resize(0);
1016 }
1017
1018 MS->EmitLabel(LineEndSym);
1019}
1020
Frederic Rissbce93ff2015-03-16 02:05:10 +00001021/// \brief Emit the pubnames or pubtypes section contribution for \p
1022/// Unit into \p Sec. The data is provided in \p Names.
1023void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001024 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001025 const std::vector<CompileUnit::AccelInfo> &Names) {
1026 if (Names.empty())
1027 return;
1028
1029 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001030 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001031 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1032 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001033
1034 bool HeaderEmitted = false;
1035 // Emit the pubnames for this compilation unit.
1036 for (const auto &Name : Names) {
1037 if (Name.SkipPubSection)
1038 continue;
1039
1040 if (!HeaderEmitted) {
1041 // Emit the header.
1042 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001043 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001044 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001045 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001046 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1047 HeaderEmitted = true;
1048 }
1049 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001050 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001051 StringRef(Name.Name.data(), Name.Name.size() + 1));
1052 }
1053
1054 if (!HeaderEmitted)
1055 return;
1056 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001057 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001058}
1059
1060/// \brief Emit .debug_pubnames for \p Unit.
1061void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1062 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1063 "names", Unit, Unit.getPubnames());
1064}
1065
1066/// \brief Emit .debug_pubtypes for \p Unit.
1067void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1068 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1069 "types", Unit, Unit.getPubtypes());
1070}
1071
Frederic Riss5a642072015-06-05 23:06:11 +00001072/// \brief Emit a CIE into the debug_frame section.
1073void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1074 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1075
1076 MS->EmitBytes(CIEBytes);
1077 FrameSectionSize += CIEBytes.size();
1078}
1079
1080/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1081/// contains the FDE data without the length, CIE offset and address
1082/// which will be replaced with the paramter values.
1083void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1084 uint32_t Address, StringRef FDEBytes) {
1085 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1086
1087 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1088 MS->EmitIntValue(CIEOffset, 4);
1089 MS->EmitIntValue(Address, AddrSize);
1090 MS->EmitBytes(FDEBytes);
1091 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1092}
1093
Frederic Rissd3455182015-01-28 18:27:01 +00001094/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001095///
1096/// The link of the dwarf information from the object files will be
1097/// driven by the selection of 'root DIEs', which are DIEs that
1098/// describe variables or functions that are present in the linked
1099/// binary (and thus have entries in the debug map). All the debug
1100/// information that will be linked (the DIEs, but also the line
1101/// tables, ranges, ...) is derived from that set of root DIEs.
1102///
1103/// The root DIEs are identified because they contain relocations that
1104/// correspond to a debug map entry at specific places (the low_pc for
1105/// a function, the location for a variable). These relocations are
1106/// called ValidRelocs in the DwarfLinker and are gathered as a very
1107/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001108class DwarfLinker {
1109public:
Frederic Rissb9818322015-02-28 00:29:07 +00001110 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1111 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001112 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001113
Frederic Rissb8b43d52015-03-04 22:07:44 +00001114 ~DwarfLinker() {
1115 for (auto *Abbrev : Abbreviations)
1116 delete Abbrev;
1117 }
1118
Frederic Rissd3455182015-01-28 18:27:01 +00001119 /// \brief Link the contents of the DebugMap.
1120 bool link(const DebugMap &);
1121
Adrian Prantlc3021ee2015-09-22 18:50:51 +00001122 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1123 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1124
Frederic Rissd3455182015-01-28 18:27:01 +00001125private:
Frederic Riss563cba62015-01-28 22:15:14 +00001126 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001127 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001128
1129 /// \brief Called at the end of a debug object link.
1130 void endDebugObject();
1131
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001132 /// Keeps track of relocations.
1133 class RelocationManager {
1134 struct ValidReloc {
1135 uint32_t Offset;
1136 uint32_t Size;
1137 uint64_t Addend;
1138 const DebugMapObject::DebugMapEntry *Mapping;
Frederic Riss1036e642015-02-13 23:18:22 +00001139
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001140 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1141 const DebugMapObject::DebugMapEntry *Mapping)
1142 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
Frederic Riss1036e642015-02-13 23:18:22 +00001143
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001144 bool operator<(const ValidReloc &RHS) const {
1145 return Offset < RHS.Offset;
1146 }
1147 };
1148
1149 DwarfLinker &Linker;
1150
1151 /// \brief The valid relocations for the current DebugMapObject.
1152 /// This vector is sorted by relocation offset.
1153 std::vector<ValidReloc> ValidRelocs;
1154
1155 /// \brief Index into ValidRelocs of the next relocation to
1156 /// consider. As we walk the DIEs in acsending file offset and as
1157 /// ValidRelocs is sorted by file offset, keeping this index
1158 /// uptodate is all we have to do to have a cheap lookup during the
1159 /// root DIE selection and during DIE cloning.
1160 unsigned NextValidReloc;
1161
1162 public:
1163 RelocationManager(DwarfLinker &Linker)
1164 : Linker(Linker), NextValidReloc(0) {}
1165
1166 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1167 /// \brief Reset the NextValidReloc counter.
1168 void resetValidRelocs() { NextValidReloc = 0; }
1169
1170 /// \defgroup FindValidRelocations Translate debug map into a list
1171 /// of relevant relocations
1172 ///
1173 /// @{
1174 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1175 const DebugMapObject &DMO);
1176
1177 bool findValidRelocs(const object::SectionRef &Section,
1178 const object::ObjectFile &Obj,
1179 const DebugMapObject &DMO);
1180
1181 void findValidRelocsMachO(const object::SectionRef &Section,
1182 const object::MachOObjectFile &Obj,
1183 const DebugMapObject &DMO);
1184 /// @}
1185
1186 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1187 CompileUnit::DIEInfo &Info);
1188
1189 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1190 bool isLittleEndian);
Frederic Riss1036e642015-02-13 23:18:22 +00001191 };
1192
Frederic Riss84c09a52015-02-13 23:18:34 +00001193 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1194 ///
1195 /// @{
1196 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1197 /// keep. Store that information in \p CU's DIEInfo.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001198 void lookForDIEsToKeep(RelocationManager &RelocMgr,
1199 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001200 const DebugMapObject &DMO, CompileUnit &CU,
1201 unsigned Flags);
1202
Adrian Prantle5162db2015-09-22 22:20:50 +00001203 /// If this compile unit is really a skeleton CU that points to a
1204 /// clang module, register it in ClangModules and return true.
1205 ///
1206 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1207 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1208 /// hash.
1209 bool registerModuleReference(const DWARFDebugInfoEntryMinimal &CUDie,
1210 const DWARFUnit &Unit, DebugMap &ModuleMap,
1211 unsigned Indent = 0);
1212
1213 /// Recursively add the debug info in this clang module .pcm
1214 /// file (and all the modules imported by it in a bottom-up fashion)
1215 /// to Units.
Adrian Prantla112ef92015-09-23 17:35:52 +00001216 void loadClangModule(StringRef Filename, StringRef ModulePath,
1217 StringRef ModuleName, uint64_t DwoId,
Adrian Prantle5162db2015-09-22 22:20:50 +00001218 DebugMap &ModuleMap, unsigned Indent = 0);
1219
Frederic Riss84c09a52015-02-13 23:18:34 +00001220 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1221 enum TravesalFlags {
1222 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1223 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1224 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1225 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001226 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss29eedc72015-09-11 04:17:30 +00001227 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
Frederic Riss84c09a52015-02-13 23:18:34 +00001228 };
1229
1230 /// \brief Mark the passed DIE as well as all the ones it depends on
1231 /// as kept.
Adrian Prantl6ec47122015-09-22 15:31:14 +00001232 void keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001233 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001234 CompileUnit::DIEInfo &MyInfo,
1235 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001236 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001237
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001238 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1239 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001240 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1241 unsigned Flags);
1242
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001243 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1244 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001245 CompileUnit &Unit,
1246 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1247
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001248 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1249 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001250 CompileUnit &Unit,
1251 CompileUnit::DIEInfo &MyInfo,
1252 unsigned Flags);
1253
1254 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1255 CompileUnit::DIEInfo &Info);
1256 /// @}
1257
Frederic Rissb8b43d52015-03-04 22:07:44 +00001258 /// \defgroup Linking Methods used to link the debug information
1259 ///
1260 /// @{
Frederic Rissb8b43d52015-03-04 22:07:44 +00001261
Adrian Prantl3565af42015-09-14 16:46:10 +00001262 class DIECloner {
1263 DwarfLinker &Linker;
1264 RelocationManager &RelocMgr;
1265 /// Allocator used for all the DIEValue objects.
1266 BumpPtrAllocator &DIEAlloc;
1267 MutableArrayRef<CompileUnit> CompileUnits;
1268 LinkOptions Options;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001269
Adrian Prantl3565af42015-09-14 16:46:10 +00001270 public:
1271 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1272 BumpPtrAllocator &DIEAlloc,
1273 MutableArrayRef<CompileUnit> CompileUnits, LinkOptions &Options)
1274 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1275 CompileUnits(CompileUnits), Options(Options) {}
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001276
Adrian Prantl3565af42015-09-14 16:46:10 +00001277 /// Recursively clone \p InputDIE into an tree of DIE objects
1278 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1279 /// stripped out and addresses have been rewritten according to the
1280 /// debug map.
1281 ///
1282 /// \param OutOffset is the offset the cloned DIE in the output
1283 /// compile unit.
1284 /// \param PCOffset (while cloning a function scope) is the offset
1285 /// applied to the entry point of the function to get the linked address.
1286 ///
1287 /// \returns the root of the cloned tree or null if nothing was selected.
Adrian Prantl3abe18d2015-09-14 23:27:26 +00001288 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Adrian Prantl3565af42015-09-14 16:46:10 +00001289 int64_t PCOffset, uint32_t OutOffset, unsigned Flags);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001290
Adrian Prantl3565af42015-09-14 16:46:10 +00001291 /// Construct the output DIE tree by cloning the DIEs we
1292 /// chose to keep above. If there are no valid relocs, then there's
1293 /// nothing to clone/emit.
1294 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001295
Adrian Prantl3565af42015-09-14 16:46:10 +00001296 private:
1297 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
Frederic Rissbce93ff2015-03-16 02:05:10 +00001298
Adrian Prantl3565af42015-09-14 16:46:10 +00001299 /// Information gathered and exchanged between the various
1300 /// clone*Attributes helpers about the attributes of a particular DIE.
1301 struct AttributesInfo {
1302 const char *Name, *MangledName; ///< Names.
1303 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
Frederic Riss31da3242015-03-11 18:45:52 +00001304
Adrian Prantl3565af42015-09-14 16:46:10 +00001305 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1306 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1307 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
Frederic Rissbce93ff2015-03-16 02:05:10 +00001308
Adrian Prantl3565af42015-09-14 16:46:10 +00001309 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1310 bool IsDeclaration; ///< Is this DIE only a declaration?
1311
1312 AttributesInfo()
1313 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1314 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1315 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1316 };
1317
1318 /// Helper for cloneDIE.
1319 unsigned cloneAttribute(DIE &Die,
1320 const DWARFDebugInfoEntryMinimal &InputDIE,
1321 CompileUnit &U, const DWARFFormValue &Val,
1322 const AttributeSpec AttrSpec, unsigned AttrSize,
1323 AttributesInfo &AttrInfo);
1324
1325 /// Clone a string attribute described by \p AttrSpec and add
1326 /// it to \p Die.
1327 /// \returns the size of the new attribute.
1328 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1329 const DWARFFormValue &Val,
1330 const DWARFUnit &U);
1331
1332 /// Clone an attribute referencing another DIE and add
1333 /// it to \p Die.
1334 /// \returns the size of the new attribute.
1335 unsigned
1336 cloneDieReferenceAttribute(DIE &Die,
1337 const DWARFDebugInfoEntryMinimal &InputDIE,
1338 AttributeSpec AttrSpec, unsigned AttrSize,
1339 const DWARFFormValue &Val, CompileUnit &Unit);
1340
1341 /// Clone an attribute referencing another DIE and add
1342 /// it to \p Die.
1343 /// \returns the size of the new attribute.
1344 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1345 const DWARFFormValue &Val, unsigned AttrSize);
1346
1347 /// Clone an attribute referencing another DIE and add
1348 /// it to \p Die.
1349 /// \returns the size of the new attribute.
1350 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1351 const DWARFFormValue &Val,
1352 const CompileUnit &Unit,
1353 AttributesInfo &Info);
1354
1355 /// Clone a scalar attribute and add it to \p Die.
1356 /// \returns the size of the new attribute.
1357 unsigned cloneScalarAttribute(DIE &Die,
1358 const DWARFDebugInfoEntryMinimal &InputDIE,
1359 CompileUnit &U, AttributeSpec AttrSpec,
1360 const DWARFFormValue &Val, unsigned AttrSize,
1361 AttributesInfo &Info);
1362
1363 /// Get the potential name and mangled name for the entity
1364 /// described by \p Die and store them in \Info if they are not
1365 /// already there.
1366 /// \returns is a name was found.
1367 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1368 AttributesInfo &Info);
1369
1370 /// Create a copy of abbreviation Abbrev.
1371 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
Frederic Riss31da3242015-03-11 18:45:52 +00001372 };
1373
Frederic Rissb8b43d52015-03-04 22:07:44 +00001374 /// \brief Assign an abbreviation number to \p Abbrev
1375 void AssignAbbrev(DIEAbbrev &Abbrev);
1376
1377 /// \brief FoldingSet that uniques the abbreviations.
1378 FoldingSet<DIEAbbrev> AbbreviationsSet;
1379 /// \brief Storage for the unique Abbreviations.
1380 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1381 /// be changed to a vecot of unique_ptrs.
1382 std::vector<DIEAbbrev *> Abbreviations;
1383
Frederic Riss25440872015-03-13 23:30:31 +00001384 /// \brief Compute and emit debug_ranges section for \p Unit, and
1385 /// patch the attributes referencing it.
1386 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1387
1388 /// \brief Generate and emit the DW_AT_ranges attribute for a
1389 /// compile_unit if it had one.
1390 void generateUnitRanges(CompileUnit &Unit) const;
1391
Frederic Riss63786b02015-03-15 20:45:43 +00001392 /// \brief Extract the line tables fromt he original dwarf, extract
1393 /// the relevant parts according to the linked function ranges and
1394 /// emit the result in the debug_line section.
1395 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1396
Frederic Rissbce93ff2015-03-16 02:05:10 +00001397 /// \brief Emit the accelerator entries for \p Unit.
1398 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1399
Frederic Riss5a642072015-06-05 23:06:11 +00001400 /// \brief Patch the frame info for an object file and emit it.
1401 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1402 unsigned AddressSize);
1403
Frederic Rissb8b43d52015-03-04 22:07:44 +00001404 /// \brief DIELoc objects that need to be destructed (but not freed!).
1405 std::vector<DIELoc *> DIELocs;
1406 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1407 std::vector<DIEBlock *> DIEBlocks;
1408 /// \brief Allocator used for all the DIEValue objects.
1409 BumpPtrAllocator DIEAlloc;
1410 /// @}
1411
Frederic Riss1c650942015-07-21 22:41:43 +00001412 /// ODR Contexts for that link.
1413 DeclContextTree ODRContexts;
1414
Frederic Riss1b9da422015-02-13 23:18:29 +00001415 /// \defgroup Helpers Various helper methods.
1416 ///
1417 /// @{
Frederic Rissc99ea202015-02-28 00:29:11 +00001418 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001419
1420 /// \brief Attempt to load a debug object from disk.
1421 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1422 DebugMapObject &Obj,
1423 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001424 /// @}
1425
Frederic Rissd3455182015-01-28 18:27:01 +00001426 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001427 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001428 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001429 std::unique_ptr<DwarfStreamer> Streamer;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001430 uint64_t OutputDebugInfoSize;
Adrian Prantle5162db2015-09-22 22:20:50 +00001431 unsigned UnitID; ///< A unique ID that identifies each compile unit.
Frederic Riss563cba62015-01-28 22:15:14 +00001432
1433 /// The units of the current debug map object.
1434 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001435
1436 /// The debug map object curently under consideration.
1437 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001438
1439 /// \brief The Dwarf string pool
1440 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001441
1442 /// \brief This map is keyed by the entry PC of functions in that
1443 /// debug object and the associated value is a pair storing the
1444 /// corresponding end PC and the offset to apply to get the linked
1445 /// address.
1446 ///
1447 /// See startDebugObject() for a more complete description of its use.
1448 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001449
1450 /// \brief The CIEs that have been emitted in the output
1451 /// section. The actual CIE data serves a the key to this StringMap,
1452 /// this takes care of comparing the semantics of CIEs defined in
1453 /// different object files.
1454 StringMap<uint32_t> EmittedCIEs;
1455
1456 /// Offset of the last CIE that has been emitted in the output
1457 /// debug_frame section.
1458 uint32_t LastCIEOffset;
Adrian Prantle5162db2015-09-22 22:20:50 +00001459
Adrian Prantl20937022015-09-23 17:11:10 +00001460 /// Mapping the PCM filename to the DwoId.
1461 StringMap<uint64_t> ClangModules;
Frederic Rissd3455182015-01-28 18:27:01 +00001462};
1463
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001464/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1465/// CompileUnit object instead.
1466static CompileUnit *getUnitForOffset(MutableArrayRef<CompileUnit> Units,
1467 unsigned Offset) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001468 auto CU =
1469 std::upper_bound(Units.begin(), Units.end(), Offset,
1470 [](uint32_t LHS, const CompileUnit &RHS) {
1471 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1472 });
1473 return CU != Units.end() ? &*CU : nullptr;
1474}
1475
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001476/// Resolve the DIE attribute reference that has been
Frederic Riss1b9da422015-02-13 23:18:29 +00001477/// extracted in \p RefValue. The resulting DIE migh be in another
1478/// CompileUnit which is stored into \p ReferencedCU.
1479/// \returns null if resolving fails for any reason.
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001480static const DWARFDebugInfoEntryMinimal *resolveDIEReference(
1481 const DwarfLinker &Linker, MutableArrayRef<CompileUnit> Units,
Frederic Riss1c650942015-07-21 22:41:43 +00001482 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001483 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1484 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1485 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1486
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001487 if ((RefCU = getUnitForOffset(Units, RefOffset)))
Frederic Riss1b9da422015-02-13 23:18:29 +00001488 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1489 return RefDie;
1490
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001491 Linker.reportWarning("could not find referenced DIE", &Unit, &DIE);
Frederic Riss1b9da422015-02-13 23:18:29 +00001492 return nullptr;
1493}
1494
Frederic Riss1c650942015-07-21 22:41:43 +00001495/// \returns whether the passed \a Attr type might contain a DIE
1496/// reference suitable for ODR uniquing.
1497static bool isODRAttribute(uint16_t Attr) {
1498 switch (Attr) {
1499 default:
1500 return false;
1501 case dwarf::DW_AT_type:
1502 case dwarf::DW_AT_containing_type:
1503 case dwarf::DW_AT_specification:
1504 case dwarf::DW_AT_abstract_origin:
1505 case dwarf::DW_AT_import:
1506 return true;
1507 }
1508 llvm_unreachable("Improper attribute.");
1509}
1510
1511/// Set the last DIE/CU a context was seen in and, possibly invalidate
1512/// the context if it is ambiguous.
1513///
1514/// In the current implementation, we don't handle overloaded
1515/// functions well, because the argument types are not taken into
1516/// account when computing the DeclContext tree.
1517///
1518/// Some of this is mitigated byt using mangled names that do contain
1519/// the arguments types, but sometimes (eg. with function templates)
1520/// we don't have that. In that case, just do not unique anything that
1521/// refers to the contexts we are not able to distinguish.
1522///
1523/// If a context that is not a namespace appears twice in the same CU,
1524/// we know it is ambiguous. Make it invalid.
1525bool DeclContext::setLastSeenDIE(CompileUnit &U,
1526 const DWARFDebugInfoEntryMinimal *Die) {
1527 if (LastSeenCompileUnitID == U.getUniqueID()) {
1528 DWARFUnit &OrigUnit = U.getOrigUnit();
1529 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1530 U.getInfo(FirstIdx).Ctxt = nullptr;
1531 return false;
1532 }
1533
1534 LastSeenCompileUnitID = U.getUniqueID();
1535 LastSeenDIE = Die;
1536 return true;
1537}
1538
Frederic Riss1c650942015-07-21 22:41:43 +00001539PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1540 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
Adrian Prantl42562c32015-10-02 00:27:08 +00001541 NonRelocatableStringpool &StringPool, bool InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001542 unsigned Tag = DIE->getTag();
1543
1544 // FIXME: dsymutil-classic compat: We should bail out here if we
1545 // have a specification or an abstract_origin. We will get the
1546 // parent context wrong here.
1547
1548 switch (Tag) {
1549 default:
1550 // By default stop gathering child contexts.
1551 return PointerIntPair<DeclContext *, 1>(nullptr);
Adrian Prantla112ef92015-09-23 17:35:52 +00001552 case dwarf::DW_TAG_module:
1553 break;
Frederic Riss1c650942015-07-21 22:41:43 +00001554 case dwarf::DW_TAG_compile_unit:
Frederic Riss1c650942015-07-21 22:41:43 +00001555 return PointerIntPair<DeclContext *, 1>(&Context);
1556 case dwarf::DW_TAG_subprogram:
1557 // Do not unique anything inside CU local functions.
1558 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1559 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1560 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1561 dwarf::DW_AT_external, 0))
1562 return PointerIntPair<DeclContext *, 1>(nullptr);
1563 // Fallthrough
1564 case dwarf::DW_TAG_member:
1565 case dwarf::DW_TAG_namespace:
1566 case dwarf::DW_TAG_structure_type:
1567 case dwarf::DW_TAG_class_type:
1568 case dwarf::DW_TAG_union_type:
1569 case dwarf::DW_TAG_enumeration_type:
1570 case dwarf::DW_TAG_typedef:
1571 // Artificial things might be ambiguous, because they might be
1572 // created on demand. For example implicitely defined constructors
1573 // are ambiguous because of the way we identify contexts, and they
1574 // won't be generated everytime everywhere.
1575 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1576 dwarf::DW_AT_artificial, 0))
1577 return PointerIntPair<DeclContext *, 1>(nullptr);
1578 break;
1579 }
1580
1581 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1582 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1583 StringRef NameRef;
1584 StringRef ShortNameRef;
1585 StringRef FileRef;
1586
1587 if (Name)
1588 NameRef = StringPool.internString(Name);
1589 else if (Tag == dwarf::DW_TAG_namespace)
1590 // FIXME: For dsymutil-classic compatibility. I think uniquing
1591 // within anonymous namespaces is wrong. There is no ODR guarantee
1592 // there.
1593 NameRef = StringPool.internString("(anonymous namespace)");
1594
1595 if (ShortName && ShortName != Name)
1596 ShortNameRef = StringPool.internString(ShortName);
1597 else
1598 ShortNameRef = NameRef;
1599
1600 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1601 Tag != dwarf::DW_TAG_union_type &&
1602 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1603 return PointerIntPair<DeclContext *, 1>(nullptr);
1604
1605 std::string File;
1606 unsigned Line = 0;
Adrian Prantl42562c32015-10-02 00:27:08 +00001607 unsigned ByteSize = UINT32_MAX;
Frederic Riss1c650942015-07-21 22:41:43 +00001608
Adrian Prantl42562c32015-10-02 00:27:08 +00001609 if (!InClangModule) {
1610 // Gather some discriminating data about the DeclContext we will be
1611 // creating: File, line number and byte size. This shouldn't be
1612 // necessary, because the ODR is just about names, but given that we
1613 // do some approximations with overloaded functions and anonymous
1614 // namespaces, use these additional data points to make the process
1615 // safer. This is disabled for clang modules, because forward
1616 // declarations of module-defined types do not have a file and line.
1617 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1618 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1619 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1620 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1621 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1622 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1623 &U.getOrigUnit())) {
1624 // FIXME: dsymutil-classic compatibility. I'd rather not
1625 // unique anything in anonymous namespaces, but if we do, then
1626 // verify that the file and line correspond.
1627 if (!Name && Tag == dwarf::DW_TAG_namespace)
1628 FileNum = 1;
Frederic Riss1c650942015-07-21 22:41:43 +00001629
Adrian Prantl42562c32015-10-02 00:27:08 +00001630 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1631 // instead of "" would allow more uniquing, but for now, do
1632 // it this way to match dsymutil-classic.
1633 if (LT->getFileNameByIndex(
1634 FileNum, "",
1635 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1636 File)) {
1637 Line = DIE->getAttributeValueAsUnsignedConstant(
1638 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
Frederic Riss1c650942015-07-21 22:41:43 +00001639#ifdef HAVE_REALPATH
Adrian Prantl42562c32015-10-02 00:27:08 +00001640 // Cache the resolved paths, because calling realpath is expansive.
1641 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1642 File = ResolvedPath;
1643 } else {
1644 char RealPath[PATH_MAX + 1];
1645 RealPath[PATH_MAX] = 0;
1646 if (::realpath(File.c_str(), RealPath))
1647 File = RealPath;
1648 U.setResolvedPath(FileNum, File);
1649 }
Frederic Riss1c650942015-07-21 22:41:43 +00001650#endif
Adrian Prantl42562c32015-10-02 00:27:08 +00001651 FileRef = StringPool.internString(File);
1652 }
Frederic Riss1c650942015-07-21 22:41:43 +00001653 }
1654 }
1655 }
1656 }
1657
1658 if (!Line && NameRef.empty())
1659 return PointerIntPair<DeclContext *, 1>(nullptr);
1660
Frederic Riss1c650942015-07-21 22:41:43 +00001661 // We hash NameRef, which is the mangled name, in order to get most
Adrian Prantla112ef92015-09-23 17:35:52 +00001662 // overloaded functions resolve correctly.
1663 //
1664 // Strictly speaking, hashing the Tag is only necessary for a
1665 // DW_TAG_module, to prevent uniquing of a module and a namespace
1666 // with the same name.
1667 //
1668 // FIXME: dsymutil-classic won't unique the same type presented
1669 // once as a struct and once as a class. Using the Tag in the fully
1670 // qualified name hash to get the same effect.
Frederic Riss1c650942015-07-21 22:41:43 +00001671 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1672
1673 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1674 // use the filename.
1675 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1676 Hash = hash_combine(Hash, FileRef);
1677
1678 // Now look if this context already exists.
1679 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1680 auto ContextIter = Contexts.find(&Key);
1681
1682 if (ContextIter == Contexts.end()) {
1683 // The context wasn't found.
1684 bool Inserted;
1685 DeclContext *NewContext =
1686 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1687 Context, DIE, U.getUniqueID());
1688 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1689 assert(Inserted && "Failed to insert DeclContext");
1690 (void)Inserted;
1691 } else if (Tag != dwarf::DW_TAG_namespace &&
1692 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1693 // The context was found, but it is ambiguous with another context
1694 // in the same file. Mark it invalid.
1695 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1696 }
1697
1698 assert(ContextIter != Contexts.end());
1699 // FIXME: dsymutil-classic compatibility. Union types aren't
1700 // uniques, but their children might be.
1701 if ((Tag == dwarf::DW_TAG_subprogram &&
1702 Context.getTag() != dwarf::DW_TAG_structure_type &&
1703 Context.getTag() != dwarf::DW_TAG_class_type) ||
1704 (Tag == dwarf::DW_TAG_union_type))
1705 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1706
1707 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1708}
1709
Adrian Prantl3565af42015-09-14 16:46:10 +00001710bool DwarfLinker::DIECloner::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1711 DWARFUnit &U, AttributesInfo &Info) {
1712 // FIXME: a bit wasteful as the first getName might return the
Frederic Rissbce93ff2015-03-16 02:05:10 +00001713 // short name.
1714 if (!Info.MangledName &&
1715 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001716 Info.MangledNameOffset =
1717 Linker.StringPool.getStringOffset(Info.MangledName);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001718
1719 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001720 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001721
1722 return Info.Name || Info.MangledName;
1723}
1724
Frederic Riss1b9da422015-02-13 23:18:29 +00001725/// \brief Report a warning to the user, optionaly including
1726/// information about a specific \p DIE related to the warning.
1727void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001728 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001729 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001730 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001731 Context = CurrentDebugObject->getObjectFilename();
1732 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001733
Frederic Rissb9818322015-02-28 00:29:07 +00001734 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001735 return;
1736
1737 errs() << " in DIE:\n";
1738 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1739 6 /* Indent */);
1740}
1741
Frederic Rissc99ea202015-02-28 00:29:11 +00001742bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1743 if (Options.NoOutput)
1744 return true;
1745
Frederic Rissb52cf522015-02-28 00:42:37 +00001746 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001747 return Streamer->init(TheTriple, OutputFilename);
1748}
1749
Adrian Prantla112ef92015-09-23 17:35:52 +00001750/// Recursive helper to build the global DeclContext information and
1751/// gather the child->parent relationships in the original compile unit.
1752///
1753/// \return true when this DIE and all of its children are only
1754/// forward declarations to types defined in external clang modules
1755/// (i.e., forward declarations that are children of a DW_TAG_module).
1756static bool analyzeContextInfo(const DWARFDebugInfoEntryMinimal *DIE,
1757 unsigned ParentIdx, CompileUnit &CU,
1758 DeclContext *CurrentDeclContext,
1759 NonRelocatableStringpool &StringPool,
1760 DeclContextTree &Contexts,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001761 bool InImportedModule = false) {
Frederic Riss563cba62015-01-28 22:15:14 +00001762 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001763 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1764
Adrian Prantla112ef92015-09-23 17:35:52 +00001765 // Clang imposes an ODR on modules(!) regardless of the language:
1766 // "The module-id should consist of only a single identifier,
1767 // which provides the name of the module being defined. Each
1768 // module shall have a single definition."
1769 //
1770 // This does not extend to the types inside the modules:
1771 // "[I]n C, this implies that if two structs are defined in
1772 // different submodules with the same name, those two types are
1773 // distinct types (but may be compatible types if their
1774 // definitions match)."
1775 //
1776 // We treat non-C++ modules like namespaces for this reason.
Adrian Prantlf3e634b2015-09-24 16:10:14 +00001777 if (DIE->getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
Adrian Prantlea8a7242015-09-23 20:44:37 +00001778 DIE->getAttributeValueAsString(&CU.getOrigUnit(), dwarf::DW_AT_name,
1779 "") != CU.getClangModuleName()) {
1780 InImportedModule = true;
1781 }
Adrian Prantla112ef92015-09-23 17:35:52 +00001782
Frederic Riss1c650942015-07-21 22:41:43 +00001783 Info.ParentIdx = ParentIdx;
Adrian Prantl42562c32015-10-02 00:27:08 +00001784 bool InClangModule = CU.isClangModule() || InImportedModule;
1785 if (CU.hasODR() || InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001786 if (CurrentDeclContext) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001787 auto PtrInvalidPair = Contexts.getChildDeclContext(
1788 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +00001789 CurrentDeclContext = PtrInvalidPair.getPointer();
1790 Info.Ctxt =
1791 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1792 } else
1793 Info.Ctxt = CurrentDeclContext = nullptr;
1794 }
Frederic Riss563cba62015-01-28 22:15:14 +00001795
Adrian Prantlea8a7242015-09-23 20:44:37 +00001796 Info.Prune = InImportedModule;
Frederic Riss563cba62015-01-28 22:15:14 +00001797 if (DIE->hasChildren())
1798 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1799 Child = Child->getSibling())
Adrian Prantla112ef92015-09-23 17:35:52 +00001800 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001801 StringPool, Contexts, InImportedModule);
Adrian Prantla112ef92015-09-23 17:35:52 +00001802
1803 // Prune this DIE if it is either a forward declaration inside a
1804 // DW_TAG_module or a DW_TAG_module that contains nothing but
1805 // forward declarations.
1806 Info.Prune &= (DIE->getTag() == dwarf::DW_TAG_module) ||
1807 DIE->getAttributeValueAsUnsignedConstant(
1808 &CU.getOrigUnit(), dwarf::DW_AT_declaration, 0);
1809
1810 return Info.Prune;
Frederic Riss563cba62015-01-28 22:15:14 +00001811}
1812
Frederic Riss84c09a52015-02-13 23:18:34 +00001813static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1814 switch (Tag) {
1815 default:
1816 return false;
1817 case dwarf::DW_TAG_subprogram:
1818 case dwarf::DW_TAG_lexical_block:
1819 case dwarf::DW_TAG_subroutine_type:
1820 case dwarf::DW_TAG_structure_type:
1821 case dwarf::DW_TAG_class_type:
1822 case dwarf::DW_TAG_union_type:
1823 return true;
1824 }
1825 llvm_unreachable("Invalid Tag");
1826}
1827
Frederic Riss1c650942015-07-21 22:41:43 +00001828static unsigned getRefAddrSize(const DWARFUnit &U) {
1829 if (U.getVersion() == 2)
1830 return U.getAddressByteSize();
1831 return 4;
1832}
1833
Frederic Riss63786b02015-03-15 20:45:43 +00001834void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001835 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss63786b02015-03-15 20:45:43 +00001836 // Iterate over the debug map entries and put all the ones that are
1837 // functions (because they have a size) into the Ranges map. This
1838 // map is very similar to the FunctionRanges that are stored in each
1839 // unit, with 2 notable differences:
1840 // - obviously this one is global, while the other ones are per-unit.
1841 // - this one contains not only the functions described in the DIE
1842 // tree, but also the ones that are only in the debug map.
1843 // The latter information is required to reproduce dsymutil's logic
1844 // while linking line tables. The cases where this information
1845 // matters look like bugs that need to be investigated, but for now
1846 // we need to reproduce dsymutil's behavior.
1847 // FIXME: Once we understood exactly if that information is needed,
1848 // maybe totally remove this (or try to use it to do a real
1849 // -gline-tables-only on Darwin.
1850 for (const auto &Entry : Obj.symbols()) {
1851 const auto &Mapping = Entry.getValue();
1852 if (Mapping.Size)
1853 Ranges[Mapping.ObjectAddress] = std::make_pair(
1854 Mapping.ObjectAddress + Mapping.Size,
1855 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1856 }
Frederic Riss563cba62015-01-28 22:15:14 +00001857}
1858
Frederic Riss1036e642015-02-13 23:18:22 +00001859void DwarfLinker::endDebugObject() {
1860 Units.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001861 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001862
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001863 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1864 (*I)->~DIEBlock();
1865 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1866 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001867
1868 DIEBlocks.clear();
1869 DIELocs.clear();
1870 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001871}
1872
1873/// \brief Iterate over the relocations of the given \p Section and
1874/// store the ones that correspond to debug map entries into the
1875/// ValidRelocs array.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001876void DwarfLinker::RelocationManager::
1877findValidRelocsMachO(const object::SectionRef &Section,
1878 const object::MachOObjectFile &Obj,
1879 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001880 StringRef Contents;
1881 Section.getContents(Contents);
1882 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1883
1884 for (const object::RelocationRef &Reloc : Section.relocations()) {
1885 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1886 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1887 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001888 uint64_t Offset64 = Reloc.getOffset();
1889 if ((RelocSize != 4 && RelocSize != 8)) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001890 Linker.reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001891 continue;
1892 }
1893 uint32_t Offset = Offset64;
1894 // Mach-o uses REL relocations, the addend is at the relocation offset.
1895 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1896
1897 auto Sym = Reloc.getSymbol();
1898 if (Sym != Obj.symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001899 ErrorOr<StringRef> SymbolName = Sym->getName();
1900 if (!SymbolName) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001901 Linker.reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001902 continue;
1903 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001904 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001905 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1906 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1907 // Do not store the addend. The addend was the address of the
1908 // symbol in the object file, the address in the binary that is
1909 // stored in the debug map doesn't need to be offseted.
1910 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1911 }
1912 }
1913}
1914
1915/// \brief Dispatch the valid relocation finding logic to the
1916/// appropriate handler depending on the object file format.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001917bool DwarfLinker::RelocationManager::findValidRelocs(
1918 const object::SectionRef &Section, const object::ObjectFile &Obj,
1919 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001920 // Dispatch to the right handler depending on the file type.
1921 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1922 findValidRelocsMachO(Section, *MachOObj, DMO);
1923 else
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001924 Linker.reportWarning(Twine("unsupported object file type: ") +
1925 Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001926
1927 if (ValidRelocs.empty())
1928 return false;
1929
1930 // Sort the relocations by offset. We will walk the DIEs linearly in
1931 // the file, this allows us to just keep an index in the relocation
1932 // array that we advance during our walk, rather than resorting to
1933 // some associative container. See DwarfLinker::NextValidReloc.
1934 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1935 return true;
1936}
1937
1938/// \brief Look for relocations in the debug_info section that match
1939/// entries in the debug map. These relocations will drive the Dwarf
1940/// link by indicating which DIEs refer to symbols present in the
1941/// linked binary.
1942/// \returns wether there are any valid relocations in the debug info.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001943bool DwarfLinker::RelocationManager::
1944findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1945 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001946 // Find the debug_info section.
1947 for (const object::SectionRef &Section : Obj.sections()) {
1948 StringRef SectionName;
1949 Section.getName(SectionName);
1950 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1951 if (SectionName != "debug_info")
1952 continue;
1953 return findValidRelocs(Section, Obj, DMO);
1954 }
1955 return false;
1956}
Frederic Riss563cba62015-01-28 22:15:14 +00001957
Frederic Riss84c09a52015-02-13 23:18:34 +00001958/// \brief Checks that there is a relocation against an actual debug
1959/// map entry between \p StartOffset and \p NextOffset.
1960///
1961/// This function must be called with offsets in strictly ascending
1962/// order because it never looks back at relocations it already 'went past'.
1963/// \returns true and sets Info.InDebugMap if it is the case.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001964bool DwarfLinker::RelocationManager::
1965hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1966 CompileUnit::DIEInfo &Info) {
Frederic Riss84c09a52015-02-13 23:18:34 +00001967 assert(NextValidReloc == 0 ||
1968 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1969 if (NextValidReloc >= ValidRelocs.size())
1970 return false;
1971
1972 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1973
1974 // We might need to skip some relocs that we didn't consider. For
1975 // example the high_pc of a discarded DIE might contain a reloc that
1976 // is in the list because it actually corresponds to the start of a
1977 // function that is in the debug map.
1978 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1979 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1980
1981 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1982 return false;
1983
1984 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001985 const auto &Mapping = ValidReloc.Mapping->getValue();
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001986 if (Linker.Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001987 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1988 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001989 uint64_t(Mapping.ObjectAddress),
1990 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001991
Frederic Rissf37964c2015-06-05 20:27:07 +00001992 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1993 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001994 Info.InDebugMap = true;
1995 return true;
1996}
1997
1998/// \brief Get the starting and ending (exclusive) offset for the
1999/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
2000/// supposed to point to the position of the first attribute described
2001/// by \p Abbrev.
2002/// \return [StartOffset, EndOffset) as a pair.
2003static std::pair<uint32_t, uint32_t>
2004getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
2005 unsigned Offset, const DWARFUnit &Unit) {
2006 DataExtractor Data = Unit.getDebugInfoExtractor();
2007
2008 for (unsigned i = 0; i < Idx; ++i)
2009 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
2010
2011 uint32_t End = Offset;
2012 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
2013
2014 return std::make_pair(Offset, End);
2015}
2016
2017/// \brief Check if a variable describing DIE should be kept.
2018/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002019unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
2020 const DWARFDebugInfoEntryMinimal &DIE,
2021 CompileUnit &Unit,
2022 CompileUnit::DIEInfo &MyInfo,
2023 unsigned Flags) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002024 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2025
2026 // Global variables with constant value can always be kept.
2027 if (!(Flags & TF_InFunctionScope) &&
2028 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
2029 MyInfo.InDebugMap = true;
2030 return Flags | TF_Keep;
2031 }
2032
2033 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
2034 if (LocationIdx == -1U)
2035 return Flags;
2036
2037 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2038 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2039 uint32_t LocationOffset, LocationEndOffset;
2040 std::tie(LocationOffset, LocationEndOffset) =
2041 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
2042
2043 // See if there is a relocation to a valid debug map entry inside
2044 // this variable's location. The order is important here. We want to
2045 // always check in the variable has a valid relocation, so that the
2046 // DIEInfo is filled. However, we don't want a static variable in a
2047 // function to force us to keep the enclosing function.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002048 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
Frederic Riss84c09a52015-02-13 23:18:34 +00002049 (Flags & TF_InFunctionScope))
2050 return Flags;
2051
Frederic Rissb9818322015-02-28 00:29:07 +00002052 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002053 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2054
2055 return Flags | TF_Keep;
2056}
2057
2058/// \brief Check if a function describing DIE should be kept.
2059/// \returns updated TraversalFlags.
2060unsigned DwarfLinker::shouldKeepSubprogramDIE(
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002061 RelocationManager &RelocMgr,
Frederic Riss84c09a52015-02-13 23:18:34 +00002062 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2063 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2064 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2065
2066 Flags |= TF_InFunctionScope;
2067
2068 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2069 if (LowPcIdx == -1U)
2070 return Flags;
2071
2072 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2073 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2074 uint32_t LowPcOffset, LowPcEndOffset;
2075 std::tie(LowPcOffset, LowPcEndOffset) =
2076 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2077
2078 uint64_t LowPc =
2079 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2080 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2081 if (LowPc == -1ULL ||
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002082 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
Frederic Riss84c09a52015-02-13 23:18:34 +00002083 return Flags;
2084
Frederic Rissb9818322015-02-28 00:29:07 +00002085 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002086 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2087
Frederic Riss1af75f72015-03-12 18:45:10 +00002088 Flags |= TF_Keep;
2089
2090 DWARFFormValue HighPcValue;
2091 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2092 reportWarning("Function without high_pc. Range will be discarded.\n",
2093 &OrigUnit, &DIE);
2094 return Flags;
2095 }
2096
2097 uint64_t HighPc;
2098 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2099 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2100 } else {
2101 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2102 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2103 }
2104
Frederic Riss63786b02015-03-15 20:45:43 +00002105 // Replace the debug map range with a more accurate one.
2106 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002107 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2108 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002109}
2110
2111/// \brief Check if a DIE should be kept.
2112/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002113unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2114 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00002115 CompileUnit &Unit,
2116 CompileUnit::DIEInfo &MyInfo,
2117 unsigned Flags) {
2118 switch (DIE.getTag()) {
2119 case dwarf::DW_TAG_constant:
2120 case dwarf::DW_TAG_variable:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002121 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002122 case dwarf::DW_TAG_subprogram:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002123 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002124 case dwarf::DW_TAG_module:
2125 case dwarf::DW_TAG_imported_module:
2126 case dwarf::DW_TAG_imported_declaration:
2127 case dwarf::DW_TAG_imported_unit:
2128 // We always want to keep these.
2129 return Flags | TF_Keep;
2130 }
2131
2132 return Flags;
2133}
2134
Frederic Riss84c09a52015-02-13 23:18:34 +00002135/// \brief Mark the passed DIE as well as all the ones it depends on
2136/// as kept.
2137///
2138/// This function is called by lookForDIEsToKeep on DIEs that are
2139/// newly discovered to be needed in the link. It recursively calls
2140/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2141/// TraversalFlags to inform it that it's not doing the primary DIE
2142/// tree walk.
Adrian Prantl6ec47122015-09-22 15:31:14 +00002143void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002144 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002145 CompileUnit::DIEInfo &MyInfo,
2146 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002147 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002148 const DWARFUnit &Unit = CU.getOrigUnit();
2149 MyInfo.Keep = true;
2150
2151 // First mark all the parent chain as kept.
2152 unsigned AncestorIdx = MyInfo.ParentIdx;
2153 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002154 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002155 lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002156 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002157 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2158 }
2159
2160 // Then we need to mark all the DIEs referenced by this DIE's
2161 // attributes as kept.
2162 DataExtractor Data = Unit.getDebugInfoExtractor();
Frederic Riss36c3cb82015-09-11 04:17:25 +00002163 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2164 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
Frederic Riss84c09a52015-02-13 23:18:34 +00002165
2166 // Mark all DIEs referenced through atttributes as kept.
2167 for (const auto &AttrSpec : Abbrev->attributes()) {
2168 DWARFFormValue Val(AttrSpec.Form);
2169
2170 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2171 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2172 continue;
2173 }
2174
2175 Val.extractValue(Data, &Offset, &Unit);
2176 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002177 if (const auto *RefDIE =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002178 resolveDIEReference(*this, MutableArrayRef<CompileUnit>(Units), Val,
2179 Unit, Die, ReferencedCU)) {
Frederic Riss1c650942015-07-21 22:41:43 +00002180 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2181 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2182 // If the referenced DIE has a DeclContext that has already been
2183 // emitted, then do not keep the one in this CU. We'll link to
2184 // the canonical DIE in cloneDieReferenceAttribute.
2185 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2186 // be necessary and could be advantageously replaced by
2187 // ReferencedCU->hasODR() && CU.hasODR().
2188 // FIXME: compatibility with dsymutil-classic. There is no
2189 // reason not to unique ref_addr references.
2190 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2191 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2192 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2193 continue;
2194
Adrian Prantla112ef92015-09-23 17:35:52 +00002195 Info.Prune = false;
Frederic Riss1c650942015-07-21 22:41:43 +00002196 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002197 lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002198 TF_Keep | TF_DependencyWalk | ODRFlag);
2199 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002200 }
2201}
2202
2203/// \brief Recursively walk the \p DIE tree and look for DIEs to
2204/// keep. Store that information in \p CU's DIEInfo.
2205///
2206/// This function is the entry point of the DIE selection
2207/// algorithm. It is expected to walk the DIE tree in file order and
2208/// (though the mediation of its helper) call hasValidRelocation() on
2209/// each DIE that might be a 'root DIE' (See DwarfLinker class
2210/// comment).
2211/// While walking the dependencies of root DIEs, this function is
2212/// also called, but during these dependency walks the file order is
2213/// not respected. The TF_DependencyWalk flag tells us which kind of
2214/// traversal we are currently doing.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002215void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2216 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002217 const DebugMapObject &DMO, CompileUnit &CU,
2218 unsigned Flags) {
Frederic Riss36c3cb82015-09-11 04:17:25 +00002219 unsigned Idx = CU.getOrigUnit().getDIEIndex(&Die);
Frederic Riss84c09a52015-02-13 23:18:34 +00002220 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2221 bool AlreadyKept = MyInfo.Keep;
Adrian Prantla112ef92015-09-23 17:35:52 +00002222 if (MyInfo.Prune)
2223 return;
Frederic Riss84c09a52015-02-13 23:18:34 +00002224
2225 // If the Keep flag is set, we are marking a required DIE's
2226 // dependencies. If our target is already marked as kept, we're all
2227 // set.
2228 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2229 return;
2230
Adrian Prantl6ec47122015-09-22 15:31:14 +00002231 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
Frederic Riss84c09a52015-02-13 23:18:34 +00002232 // because it would screw up the relocation finding logic.
2233 if (!(Flags & TF_DependencyWalk))
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002234 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002235
2236 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002237 if (!AlreadyKept && (Flags & TF_Keep)) {
2238 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
Adrian Prantl6ec47122015-09-22 15:31:14 +00002239 keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
Frederic Riss1c650942015-07-21 22:41:43 +00002240 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002241 // The TF_ParentWalk flag tells us that we are currently walking up
2242 // the parent chain of a required DIE, and we don't want to mark all
2243 // the children of the parents as kept (consider for example a
2244 // DW_TAG_namespace node in the parent chain). There are however a
2245 // set of DIE types for which we want to ignore that directive and still
2246 // walk their children.
Frederic Riss36c3cb82015-09-11 04:17:25 +00002247 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
Frederic Riss84c09a52015-02-13 23:18:34 +00002248 Flags &= ~TF_ParentWalk;
2249
Frederic Riss36c3cb82015-09-11 04:17:25 +00002250 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
Frederic Riss84c09a52015-02-13 23:18:34 +00002251 return;
2252
Frederic Riss36c3cb82015-09-11 04:17:25 +00002253 for (auto *Child = Die.getFirstChild(); Child && !Child->isNULL();
Frederic Riss84c09a52015-02-13 23:18:34 +00002254 Child = Child->getSibling())
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002255 lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002256}
2257
Frederic Rissb8b43d52015-03-04 22:07:44 +00002258/// \brief Assign an abbreviation numer to \p Abbrev.
2259///
2260/// Our DIEs get freed after every DebugMapObject has been processed,
2261/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2262/// the instances hold by the DIEs. When we encounter an abbreviation
2263/// that we don't know, we create a permanent copy of it.
2264void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2265 // Check the set for priors.
2266 FoldingSetNodeID ID;
2267 Abbrev.Profile(ID);
2268 void *InsertToken;
2269 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2270
2271 // If it's newly added.
2272 if (InSet) {
2273 // Assign existing abbreviation number.
2274 Abbrev.setNumber(InSet->getNumber());
2275 } else {
2276 // Add to abbreviation list.
2277 Abbreviations.push_back(
2278 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2279 for (const auto &Attr : Abbrev.getData())
2280 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2281 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2282 // Assign the unique abbreviation number.
2283 Abbrev.setNumber(Abbreviations.size());
2284 Abbreviations.back()->setNumber(Abbreviations.size());
2285 }
2286}
2287
Adrian Prantl3565af42015-09-14 16:46:10 +00002288unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2289 AttributeSpec AttrSpec,
2290 const DWARFFormValue &Val,
2291 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002292 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002293 const char *String = *Val.getAsCString(&U);
Adrian Prantl3565af42015-09-14 16:46:10 +00002294 unsigned Offset = Linker.StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002295 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002296 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002297 return 4;
2298}
2299
Adrian Prantl3565af42015-09-14 16:46:10 +00002300unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
Frederic Riss9833de62015-03-06 23:22:53 +00002301 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2302 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002303 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002304 const DWARFUnit &U = Unit.getOrigUnit();
2305 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002306 DIE *NewRefDie = nullptr;
2307 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002308 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002309
Frederic Riss1c650942015-07-21 22:41:43 +00002310 const DWARFDebugInfoEntryMinimal *RefDie =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002311 resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE, RefUnit);
Frederic Riss1c650942015-07-21 22:41:43 +00002312
2313 // If the referenced DIE is not found, drop the attribute.
2314 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002315 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002316
2317 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2318 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002319
2320 // If we already have emitted an equivalent DeclContext, just point
2321 // at it.
2322 if (isODRAttribute(AttrSpec.Attr)) {
2323 Ctxt = RefInfo.Ctxt;
2324 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2325 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2326 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2327 dwarf::DW_FORM_ref_addr, Attr);
2328 return getRefAddrSize(U);
2329 }
2330 }
2331
Frederic Riss9833de62015-03-06 23:22:53 +00002332 if (!RefInfo.Clone) {
2333 assert(Ref > InputDIE.getOffset());
2334 // We haven't cloned this DIE yet. Just create an empty one and
2335 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002336 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002337 }
2338 NewRefDie = RefInfo.Clone;
2339
Frederic Riss1c650942015-07-21 22:41:43 +00002340 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2341 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002342 // We cannot currently rely on a DIEEntry to emit ref_addr
2343 // references, because the implementation calls back to DwarfDebug
2344 // to find the unit offset. (We don't have a DwarfDebug)
2345 // FIXME: we should be able to design DIEEntry reliance on
2346 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002347 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002348 if (Ref < InputDIE.getOffset()) {
2349 // We must have already cloned that DIE.
2350 uint32_t NewRefOffset =
2351 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002352 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002353 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2354 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002355 } else {
2356 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002357 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002358 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002359 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002360 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2361 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002362 }
Frederic Riss1c650942015-07-21 22:41:43 +00002363 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002364 }
2365
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002366 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2367 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002368 return AttrSize;
2369}
2370
Adrian Prantl3565af42015-09-14 16:46:10 +00002371unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2372 AttributeSpec AttrSpec,
2373 const DWARFFormValue &Val,
2374 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002375 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002376 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002377 DIELoc *Loc = nullptr;
2378 DIEBlock *Block = nullptr;
2379 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002380 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002381 Loc = new (DIEAlloc) DIELoc;
Adrian Prantl3565af42015-09-14 16:46:10 +00002382 Linker.DIELocs.push_back(Loc);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002383 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002384 Block = new (DIEAlloc) DIEBlock;
Adrian Prantl3565af42015-09-14 16:46:10 +00002385 Linker.DIEBlocks.push_back(Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002386 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002387 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2388 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002389
2390 if (Loc)
2391 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2392 dwarf::Form(AttrSpec.Form), Loc);
2393 else
2394 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2395 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002396 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2397 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002398 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2399 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002400 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2401 // the DIE class, this if could be replaced by
2402 // Attr->setSize(Bytes.size()).
Adrian Prantl3565af42015-09-14 16:46:10 +00002403 if (Linker.Streamer) {
2404 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002405 if (Loc)
Adrian Prantl3565af42015-09-14 16:46:10 +00002406 Loc->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002407 else
Adrian Prantl3565af42015-09-14 16:46:10 +00002408 Block->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002409 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002410 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002411 return AttrSize;
2412}
2413
Adrian Prantl3565af42015-09-14 16:46:10 +00002414unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2415 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2416 const CompileUnit &Unit, AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002417 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002418 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2419 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2420 Die.getTag() == dwarf::DW_TAG_lexical_block)
Frederic Riss7b5563a2015-08-31 01:43:14 +00002421 // The low_pc of a block or inline subroutine might get
2422 // relocated because it happens to match the low_pc of the
2423 // enclosing subprogram. To prevent issues with that, always use
2424 // the low_pc from the input DIE if relocations have been applied.
2425 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2426 Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002427 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2428 Addr = Unit.getLowPc();
2429 if (Addr == UINT64_MAX)
2430 return 0;
2431 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002432 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002433 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002434 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2435 if (uint64_t HighPc = Unit.getHighPc())
2436 Addr = HighPc;
2437 else
2438 return 0;
2439 } else
2440 // If we have a high_pc recorded for the input DIE, use
2441 // it. Otherwise (when no relocations where applied) just use the
2442 // one we just decoded.
2443 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002444 }
2445
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002446 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002447 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002448 return Unit.getOrigUnit().getAddressByteSize();
2449}
2450
Adrian Prantl3565af42015-09-14 16:46:10 +00002451unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002452 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002453 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002454 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002455 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002456 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2457 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2458 if (Unit.getLowPc() == -1ULL)
2459 return 0;
2460 // Dwarf >= 4 high_pc is an size, not an address.
2461 Value = Unit.getHighPc() - Unit.getLowPc();
2462 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002463 Value = *Val.getAsSectionOffset();
2464 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2465 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002466 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2467 Value = *OptionalValue;
2468 else {
Adrian Prantl3565af42015-09-14 16:46:10 +00002469 Linker.reportWarning(
2470 "Unsupported scalar attribute form. Dropping attribute.",
2471 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002472 return 0;
2473 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002474 PatchLocation Patch =
2475 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2476 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002477 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002478 Unit.noteRangeAttribute(Die, Patch);
Frederic Riss29eedc72015-09-11 04:17:30 +00002479
Frederic Rissdfb97902015-03-14 15:49:07 +00002480 // A more generic way to check for location attributes would be
2481 // nice, but it's very unlikely that any other attribute needs a
2482 // location list.
2483 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2484 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002485 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002486 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2487 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002488
Frederic Rissb8b43d52015-03-04 22:07:44 +00002489 return AttrSize;
2490}
2491
2492/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2493/// value \p Val, and add it to \p Die.
2494/// \returns the size of the cloned attribute.
Adrian Prantl3565af42015-09-14 16:46:10 +00002495unsigned DwarfLinker::DIECloner::cloneAttribute(
2496 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2497 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2498 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002499 const DWARFUnit &U = Unit.getOrigUnit();
2500
2501 switch (AttrSpec.Form) {
2502 case dwarf::DW_FORM_strp:
2503 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002504 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002505 case dwarf::DW_FORM_ref_addr:
2506 case dwarf::DW_FORM_ref1:
2507 case dwarf::DW_FORM_ref2:
2508 case dwarf::DW_FORM_ref4:
2509 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002510 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002511 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002512 case dwarf::DW_FORM_block:
2513 case dwarf::DW_FORM_block1:
2514 case dwarf::DW_FORM_block2:
2515 case dwarf::DW_FORM_block4:
2516 case dwarf::DW_FORM_exprloc:
2517 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2518 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002519 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002520 case dwarf::DW_FORM_data1:
2521 case dwarf::DW_FORM_data2:
2522 case dwarf::DW_FORM_data4:
2523 case dwarf::DW_FORM_data8:
2524 case dwarf::DW_FORM_udata:
2525 case dwarf::DW_FORM_sdata:
2526 case dwarf::DW_FORM_sec_offset:
2527 case dwarf::DW_FORM_flag:
2528 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002529 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2530 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002531 default:
Adrian Prantl3565af42015-09-14 16:46:10 +00002532 Linker.reportWarning(
2533 "Unsupported attribute form in cloneAttribute. Dropping.", &U,
2534 &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002535 }
2536
2537 return 0;
2538}
2539
Frederic Riss23e20e92015-03-07 01:25:09 +00002540/// \brief Apply the valid relocations found by findValidRelocs() to
2541/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2542/// in the debug_info section.
2543///
2544/// Like for findValidRelocs(), this function must be called with
2545/// monotonic \p BaseOffset values.
2546///
2547/// \returns wether any reloc has been applied.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002548bool DwarfLinker::RelocationManager::
2549applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2550 bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002551 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002552 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2553 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002554 if (NextValidReloc >= ValidRelocs.size())
2555 return false;
2556
2557 // Skip relocs that haven't been applied.
2558 while (NextValidReloc < ValidRelocs.size() &&
2559 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2560 ++NextValidReloc;
2561
2562 bool Applied = false;
2563 uint64_t EndOffset = BaseOffset + Data.size();
2564 while (NextValidReloc < ValidRelocs.size() &&
2565 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2566 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2567 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2568 assert(ValidReloc.Offset - BaseOffset < Data.size());
2569 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2570 char Buf[8];
2571 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2572 Value += ValidReloc.Addend;
2573 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2574 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2575 Buf[i] = uint8_t(Value >> (Index * 8));
2576 }
2577 assert(ValidReloc.Size <= sizeof(Buf));
2578 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2579 Applied = true;
2580 }
2581
2582 return Applied;
2583}
2584
Frederic Rissbce93ff2015-03-16 02:05:10 +00002585static bool isTypeTag(uint16_t Tag) {
2586 switch (Tag) {
2587 case dwarf::DW_TAG_array_type:
2588 case dwarf::DW_TAG_class_type:
2589 case dwarf::DW_TAG_enumeration_type:
2590 case dwarf::DW_TAG_pointer_type:
2591 case dwarf::DW_TAG_reference_type:
2592 case dwarf::DW_TAG_string_type:
2593 case dwarf::DW_TAG_structure_type:
2594 case dwarf::DW_TAG_subroutine_type:
2595 case dwarf::DW_TAG_typedef:
2596 case dwarf::DW_TAG_union_type:
2597 case dwarf::DW_TAG_ptr_to_member_type:
2598 case dwarf::DW_TAG_set_type:
2599 case dwarf::DW_TAG_subrange_type:
2600 case dwarf::DW_TAG_base_type:
2601 case dwarf::DW_TAG_const_type:
2602 case dwarf::DW_TAG_constant:
2603 case dwarf::DW_TAG_file_type:
2604 case dwarf::DW_TAG_namelist:
2605 case dwarf::DW_TAG_packed_type:
2606 case dwarf::DW_TAG_volatile_type:
2607 case dwarf::DW_TAG_restrict_type:
2608 case dwarf::DW_TAG_interface_type:
2609 case dwarf::DW_TAG_unspecified_type:
2610 case dwarf::DW_TAG_shared_type:
2611 return true;
2612 default:
2613 break;
2614 }
2615 return false;
2616}
2617
Frederic Riss29eedc72015-09-11 04:17:30 +00002618static bool
2619shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2620 uint16_t Tag, bool InDebugMap, bool SkipPC,
2621 bool InFunctionScope) {
2622 switch (AttrSpec.Attr) {
2623 default:
2624 return false;
2625 case dwarf::DW_AT_low_pc:
2626 case dwarf::DW_AT_high_pc:
2627 case dwarf::DW_AT_ranges:
2628 return SkipPC;
2629 case dwarf::DW_AT_location:
2630 case dwarf::DW_AT_frame_base:
2631 // FIXME: for some reason dsymutil-classic keeps the location
2632 // attributes when they are of block type (ie. not location
2633 // lists). This is totally wrong for globals where we will keep a
2634 // wrong address. It is mostly harmless for locals, but there is
2635 // no point in keeping these anyway when the function wasn't linked.
2636 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2637 !InDebugMap)) &&
2638 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2639 }
2640}
2641
Adrian Prantl3565af42015-09-14 16:46:10 +00002642DIE *DwarfLinker::DIECloner::cloneDIE(
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002643 const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2644 int64_t PCOffset, uint32_t OutOffset, unsigned Flags) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002645 DWARFUnit &U = Unit.getOrigUnit();
2646 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002647 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002648
2649 // Should the DIE appear in the output?
2650 if (!Unit.getInfo(Idx).Keep)
2651 return nullptr;
2652
2653 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002654 // The DIE might have been already created by a forward reference
2655 // (see cloneDieReferenceAttribute()).
2656 DIE *Die = Info.Clone;
2657 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002658 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002659 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002660 Die->setOffset(OutOffset);
Adrian Prantla112ef92015-09-23 17:35:52 +00002661 if ((Unit.hasODR() || Unit.isClangModule()) &&
2662 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
Frederic Riss1c650942015-07-21 22:41:43 +00002663 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2664 !Info.Ctxt->getCanonicalDIEOffset()) {
2665 // We are about to emit a DIE that is the root of its own valid
2666 // DeclContext tree. Make the current offset the canonical offset
2667 // for this context.
2668 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2669 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002670
2671 // Extract and clone every attribute.
2672 DataExtractor Data = U.getDebugInfoExtractor();
Adrian Prantle5162db2015-09-22 22:20:50 +00002673 // Point to the next DIE (generally there is always at least a NULL
2674 // entry after the current one). If this is a lone
2675 // DW_TAG_compile_unit without any children, point to the next unit.
2676 uint32_t NextOffset =
2677 (Idx + 1 < U.getNumDIEs())
2678 ? U.getDIEAtIndex(Idx + 1)->getOffset()
2679 : U.getNextUnitOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002680 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002681
2682 // We could copy the data only if we need to aply a relocation to
2683 // it. After testing, it seems there is no performance downside to
2684 // doing the copy unconditionally, and it makes the code simpler.
2685 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2686 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2687 // Modify the copy with relocated addresses.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002688 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
Frederic Riss31da3242015-03-11 18:45:52 +00002689 // If we applied relocations, we store the value of high_pc that was
2690 // potentially stored in the input DIE. If high_pc is an address
2691 // (Dwarf version == 2), then it might have been relocated to a
2692 // totally unrelated value (because the end address in the object
2693 // file might be start address of another function which got moved
2694 // independantly by the linker). The computation of the actual
2695 // high_pc value is done in cloneAddressAttribute().
2696 AttrInfo.OrigHighPc =
2697 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
Frederic Riss7b5563a2015-08-31 01:43:14 +00002698 // Also store the low_pc. It might get relocated in an
2699 // inline_subprogram that happens at the beginning of its
2700 // inlining function.
2701 AttrInfo.OrigLowPc =
2702 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
Frederic Riss31da3242015-03-11 18:45:52 +00002703 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002704
2705 // Reset the Offset to 0 as we will be working on the local copy of
2706 // the data.
2707 Offset = 0;
2708
Frederic Rissb8b43d52015-03-04 22:07:44 +00002709 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2710 Offset += getULEB128Size(Abbrev->getCode());
2711
Frederic Riss31da3242015-03-11 18:45:52 +00002712 // We are entering a subprogram. Get and propagate the PCOffset.
2713 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2714 PCOffset = Info.AddrAdjust;
2715 AttrInfo.PCOffset = PCOffset;
2716
Frederic Riss29eedc72015-09-11 04:17:30 +00002717 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2718 Flags |= TF_InFunctionScope;
2719 if (!Info.InDebugMap)
2720 Flags |= TF_SkipPC;
2721 }
2722
2723 bool Copied = false;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002724 for (const auto &AttrSpec : Abbrev->attributes()) {
Frederic Riss29eedc72015-09-11 04:17:30 +00002725 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2726 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2727 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2728 // FIXME: dsymutil-classic keeps the old abbreviation around
2729 // even if it's not used. We can remove this (and the copyAbbrev
2730 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2731 if (!Copied) {
2732 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2733 Copied = true;
2734 }
2735 continue;
2736 }
2737
Frederic Rissb8b43d52015-03-04 22:07:44 +00002738 DWARFFormValue Val(AttrSpec.Form);
2739 uint32_t AttrSize = Offset;
2740 Val.extractValue(Data, &Offset, &U);
2741 AttrSize = Offset - AttrSize;
2742
Frederic Riss31da3242015-03-11 18:45:52 +00002743 OutOffset +=
2744 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002745 }
2746
Frederic Rissbce93ff2015-03-16 02:05:10 +00002747 // Look for accelerator entries.
2748 uint16_t Tag = InputDIE.getTag();
2749 // FIXME: This is slightly wrong. An inline_subroutine without a
2750 // low_pc, but with AT_ranges might be interesting to get into the
2751 // accelerator tables too. For now stick with dsymutil's behavior.
2752 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2753 Tag != dwarf::DW_TAG_compile_unit &&
2754 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2755 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2756 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2757 AttrInfo.MangledNameOffset,
2758 Tag == dwarf::DW_TAG_inlined_subroutine);
2759 if (AttrInfo.Name)
2760 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2761 Tag == dwarf::DW_TAG_inlined_subroutine);
2762 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2763 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2764 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2765 }
2766
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002767 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002768 // If a scope DIE is kept, we must have kept at least one child. If
2769 // it's not the case, we'll just be emitting one wasteful end of
2770 // children marker, but things won't break.
2771 if (InputDIE.hasChildren())
2772 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2773 // Assign a permanent abbrev number
Adrian Prantl3565af42015-09-14 16:46:10 +00002774 Linker.AssignAbbrev(NewAbbrev);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002775 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002776
2777 // Add the size of the abbreviation number to the output offset.
2778 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2779
2780 if (!Abbrev->hasChildren()) {
2781 // Update our size.
2782 Die->setSize(OutOffset - Die->getOffset());
2783 return Die;
2784 }
2785
2786 // Recursively clone children.
2787 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2788 Child = Child->getSibling()) {
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002789 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset, Flags)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002790 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002791 OutOffset = Clone->getOffset() + Clone->getSize();
2792 }
2793 }
2794
2795 // Account for the end of children marker.
2796 OutOffset += sizeof(int8_t);
2797 // Update our size.
2798 Die->setSize(OutOffset - Die->getOffset());
2799 return Die;
2800}
2801
Frederic Riss25440872015-03-13 23:30:31 +00002802/// \brief Patch the input object file relevant debug_ranges entries
2803/// and emit them in the output file. Update the relevant attributes
2804/// to point at the new entries.
2805void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2806 DWARFContext &OrigDwarf) const {
2807 DWARFDebugRangeList RangeList;
2808 const auto &FunctionRanges = Unit.getFunctionRanges();
2809 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2810 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2811 OrigDwarf.isLittleEndian(), AddressSize);
2812 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2813 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002814 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002815 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2816 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2817 // Ranges addresses are based on the unit's low_pc. Compute the
2818 // offset we need to apply to adapt to the the new unit's low_pc.
2819 int64_t UnitPcOffset = 0;
2820 if (OrigLowPc != -1ULL)
2821 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2822
2823 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002824 uint32_t Offset = RangeAttribute.get();
2825 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002826 RangeList.extract(RangeExtractor, &Offset);
2827 const auto &Entries = RangeList.getEntries();
Frederic Riss94546202015-08-31 05:09:32 +00002828 if (!Entries.empty()) {
2829 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
Frederic Riss25440872015-03-13 23:30:31 +00002830
Frederic Riss25440872015-03-13 23:30:31 +00002831 if (CurrRange == InvalidRange ||
Frederic Riss94546202015-08-31 05:09:32 +00002832 First.StartAddress + OrigLowPc < CurrRange.start() ||
2833 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2834 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2835 if (CurrRange == InvalidRange ||
2836 CurrRange.start() > First.StartAddress + OrigLowPc) {
2837 reportWarning("no mapping for range.");
2838 continue;
2839 }
Frederic Riss25440872015-03-13 23:30:31 +00002840 }
2841 }
2842
2843 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2844 AddressSize);
2845 }
2846}
2847
Frederic Riss563b1b02015-03-14 03:46:51 +00002848/// \brief Generate the debug_aranges entries for \p Unit and if the
2849/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2850/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002851/// FIXME: this could actually be done right in patchRangesForUnit,
2852/// but for the sake of initial bit-for-bit compatibility with legacy
2853/// dsymutil, we have to do it in a delayed pass.
2854void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002855 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002856 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002857 Attr->set(Streamer->getRangesSectionSize());
2858 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002859}
2860
Frederic Riss63786b02015-03-15 20:45:43 +00002861/// \brief Insert the new line info sequence \p Seq into the current
2862/// set of already linked line info \p Rows.
2863static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2864 std::vector<DWARFDebugLine::Row> &Rows) {
2865 if (Seq.empty())
2866 return;
2867
2868 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2869 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2870 Seq.clear();
2871 return;
2872 }
2873
2874 auto InsertPoint = std::lower_bound(
2875 Rows.begin(), Rows.end(), Seq.front(),
2876 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2877 return LHS.Address < RHS.Address;
2878 });
2879
2880 // FIXME: this only removes the unneeded end_sequence if the
2881 // sequences have been inserted in order. using a global sort like
2882 // described in patchLineTableForUnit() and delaying the end_sequene
2883 // elimination to emitLineTableForUnit() we can get rid of all of them.
2884 if (InsertPoint != Rows.end() &&
2885 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2886 *InsertPoint = Seq.front();
2887 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2888 } else {
2889 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2890 }
2891
2892 Seq.clear();
2893}
2894
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002895static void patchStmtList(DIE &Die, DIEInteger Offset) {
2896 for (auto &V : Die.values())
2897 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002898 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002899 return;
2900 }
2901
2902 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2903}
2904
Frederic Riss63786b02015-03-15 20:45:43 +00002905/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2906/// recreate a relocated version of these for the address ranges that
2907/// are present in the binary.
2908void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2909 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002910 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002911 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2912 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2913 if (StmtList == -1ULL)
2914 return;
2915
2916 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002917 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2918 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002919
2920 // Parse the original line info for the unit.
2921 DWARFDebugLine::LineTable LineTable;
2922 uint32_t StmtOffset = StmtList;
2923 StringRef LineData = OrigDwarf.getLineSection().Data;
2924 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2925 Unit.getOrigUnit().getAddressByteSize());
2926 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2927 &StmtOffset);
2928
2929 // This vector is the output line table.
2930 std::vector<DWARFDebugLine::Row> NewRows;
2931 NewRows.reserve(LineTable.Rows.size());
2932
2933 // Current sequence of rows being extracted, before being inserted
2934 // in NewRows.
2935 std::vector<DWARFDebugLine::Row> Seq;
2936 const auto &FunctionRanges = Unit.getFunctionRanges();
2937 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2938
2939 // FIXME: This logic is meant to generate exactly the same output as
2940 // Darwin's classic dsynutil. There is a nicer way to implement this
2941 // by simply putting all the relocated line info in NewRows and simply
2942 // sorting NewRows before passing it to emitLineTableForUnit. This
2943 // should be correct as sequences for a function should stay
2944 // together in the sorted output. There are a few corner cases that
2945 // look suspicious though, and that required to implement the logic
2946 // this way. Revisit that once initial validation is finished.
2947
2948 // Iterate over the object file line info and extract the sequences
2949 // that correspond to linked functions.
2950 for (auto &Row : LineTable.Rows) {
2951 // Check wether we stepped out of the range. The range is
2952 // half-open, but consider accept the end address of the range if
2953 // it is marked as end_sequence in the input (because in that
2954 // case, the relocation offset is accurate and that entry won't
2955 // serve as the start of another function).
2956 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2957 Row.Address > CurrRange.stop() ||
2958 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2959 // We just stepped out of a known range. Insert a end_sequence
2960 // corresponding to the end of the range.
2961 uint64_t StopAddress = CurrRange != InvalidRange
2962 ? CurrRange.stop() + CurrRange.value()
2963 : -1ULL;
2964 CurrRange = FunctionRanges.find(Row.Address);
2965 bool CurrRangeValid =
2966 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2967 if (!CurrRangeValid) {
2968 CurrRange = InvalidRange;
2969 if (StopAddress != -1ULL) {
2970 // Try harder by looking in the DebugMapObject function
2971 // ranges map. There are corner cases where this finds a
2972 // valid entry. It's unclear if this is right or wrong, but
2973 // for now do as dsymutil.
2974 // FIXME: Understand exactly what cases this addresses and
2975 // potentially remove it along with the Ranges map.
2976 auto Range = Ranges.lower_bound(Row.Address);
2977 if (Range != Ranges.begin() && Range != Ranges.end())
2978 --Range;
2979
2980 if (Range != Ranges.end() && Range->first <= Row.Address &&
2981 Range->second.first >= Row.Address) {
2982 StopAddress = Row.Address + Range->second.second;
2983 }
2984 }
2985 }
2986 if (StopAddress != -1ULL && !Seq.empty()) {
2987 // Insert end sequence row with the computed end address, but
2988 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00002989 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00002990 NextLine.Address = StopAddress;
2991 NextLine.EndSequence = 1;
2992 NextLine.PrologueEnd = 0;
2993 NextLine.BasicBlock = 0;
2994 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00002995 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00002996 insertLineSequence(Seq, NewRows);
2997 }
2998
2999 if (!CurrRangeValid)
3000 continue;
3001 }
3002
3003 // Ignore empty sequences.
3004 if (Row.EndSequence && Seq.empty())
3005 continue;
3006
3007 // Relocate row address and add it to the current sequence.
3008 Row.Address += CurrRange.value();
3009 Seq.emplace_back(Row);
3010
3011 if (Row.EndSequence)
3012 insertLineSequence(Seq, NewRows);
3013 }
3014
3015 // Finished extracting, now emit the line tables.
3016 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
3017 // FIXME: LLVM hardcodes it's prologue values. We just copy the
3018 // prologue over and that works because we act as both producer and
3019 // consumer. It would be nicer to have a real configurable line
3020 // table emitter.
3021 if (LineTable.Prologue.Version != 2 ||
3022 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00003023 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00003024 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00003025 else {
3026 MCDwarfLineTableParams Params;
3027 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
3028 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
3029 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
3030 Streamer->emitLineTableForUnit(Params,
3031 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00003032 LineTable.Prologue.MinInstLength, NewRows,
3033 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00003034 }
Frederic Riss63786b02015-03-15 20:45:43 +00003035}
3036
Frederic Rissbce93ff2015-03-16 02:05:10 +00003037void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
3038 Streamer->emitPubNamesForUnit(Unit);
3039 Streamer->emitPubTypesForUnit(Unit);
3040}
3041
Frederic Riss5a642072015-06-05 23:06:11 +00003042/// \brief Read the frame info stored in the object, and emit the
3043/// patched frame descriptions for the linked binary.
3044///
3045/// This is actually pretty easy as the data of the CIEs and FDEs can
3046/// be considered as black boxes and moved as is. The only thing to do
3047/// is to patch the addresses in the headers.
3048void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3049 DWARFContext &OrigDwarf,
3050 unsigned AddrSize) {
3051 StringRef FrameData = OrigDwarf.getDebugFrameSection();
3052 if (FrameData.empty())
3053 return;
3054
3055 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3056 uint32_t InputOffset = 0;
3057
3058 // Store the data of the CIEs defined in this object, keyed by their
3059 // offsets.
3060 DenseMap<uint32_t, StringRef> LocalCIES;
3061
3062 while (Data.isValidOffset(InputOffset)) {
3063 uint32_t EntryOffset = InputOffset;
3064 uint32_t InitialLength = Data.getU32(&InputOffset);
3065 if (InitialLength == 0xFFFFFFFF)
3066 return reportWarning("Dwarf64 bits no supported");
3067
3068 uint32_t CIEId = Data.getU32(&InputOffset);
3069 if (CIEId == 0xFFFFFFFF) {
3070 // This is a CIE, store it.
3071 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3072 LocalCIES[EntryOffset] = CIEData;
3073 // The -4 is to account for the CIEId we just read.
3074 InputOffset += InitialLength - 4;
3075 continue;
3076 }
3077
3078 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3079
3080 // Some compilers seem to emit frame info that doesn't start at
3081 // the function entry point, thus we can't just lookup the address
3082 // in the debug map. Use the linker's range map to see if the FDE
3083 // describes something that we can relocate.
3084 auto Range = Ranges.upper_bound(Loc);
3085 if (Range != Ranges.begin())
3086 --Range;
3087 if (Range == Ranges.end() || Range->first > Loc ||
3088 Range->second.first <= Loc) {
3089 // The +4 is to account for the size of the InitialLength field itself.
3090 InputOffset = EntryOffset + InitialLength + 4;
3091 continue;
3092 }
3093
3094 // This is an FDE, and we have a mapping.
3095 // Have we already emitted a corresponding CIE?
3096 StringRef CIEData = LocalCIES[CIEId];
3097 if (CIEData.empty())
3098 return reportWarning("Inconsistent debug_frame content. Dropping.");
3099
3100 // Look if we already emitted a CIE that corresponds to the
3101 // referenced one (the CIE data is the key of that lookup).
3102 auto IteratorInserted = EmittedCIEs.insert(
3103 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3104 // If there is no CIE yet for this ID, emit it.
3105 if (IteratorInserted.second ||
3106 // FIXME: dsymutil-classic only caches the last used CIE for
3107 // reuse. Mimic that behavior for now. Just removing that
3108 // second half of the condition and the LastCIEOffset variable
3109 // makes the code DTRT.
3110 LastCIEOffset != IteratorInserted.first->getValue()) {
3111 LastCIEOffset = Streamer->getFrameSectionSize();
3112 IteratorInserted.first->getValue() = LastCIEOffset;
3113 Streamer->emitCIE(CIEData);
3114 }
3115
3116 // Emit the FDE with updated address and CIE pointer.
3117 // (4 + AddrSize) is the size of the CIEId + initial_location
3118 // fields that will get reconstructed by emitFDE().
3119 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3120 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3121 Loc + Range->second.second,
3122 FrameData.substr(InputOffset, FDERemainingBytes));
3123 InputOffset += FDERemainingBytes;
3124 }
3125}
3126
Adrian Prantl3565af42015-09-14 16:46:10 +00003127void DwarfLinker::DIECloner::copyAbbrev(
3128 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
Frederic Riss29eedc72015-09-11 04:17:30 +00003129 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3130 dwarf::Form(Abbrev.hasChildren()));
3131
3132 for (const auto &Attr : Abbrev.attributes()) {
3133 uint16_t Form = Attr.Form;
3134 if (hasODR && isODRAttribute(Attr.Attr))
3135 Form = dwarf::DW_FORM_ref_addr;
3136 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3137 }
3138
Adrian Prantl3565af42015-09-14 16:46:10 +00003139 Linker.AssignAbbrev(Copy);
Frederic Riss29eedc72015-09-11 04:17:30 +00003140}
3141
Adrian Prantl20937022015-09-23 17:11:10 +00003142static uint64_t getDwoId(const DWARFDebugInfoEntryMinimal &CUDie,
3143 const DWARFUnit &Unit) {
3144 uint64_t DwoId =
3145 CUDie.getAttributeValueAsUnsignedConstant(&Unit, dwarf::DW_AT_dwo_id, 0);
3146 if (!DwoId)
3147 DwoId = CUDie.getAttributeValueAsUnsignedConstant(&Unit,
3148 dwarf::DW_AT_GNU_dwo_id, 0);
3149 return DwoId;
3150}
3151
Adrian Prantle5162db2015-09-22 22:20:50 +00003152bool DwarfLinker::registerModuleReference(
3153 const DWARFDebugInfoEntryMinimal &CUDie, const DWARFUnit &Unit,
3154 DebugMap &ModuleMap, unsigned Indent) {
3155 std::string PCMfile =
Adrian Prantl20937022015-09-23 17:11:10 +00003156 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_dwo_name, "");
3157 if (PCMfile.empty())
3158 PCMfile =
3159 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_GNU_dwo_name, "");
Adrian Prantle5162db2015-09-22 22:20:50 +00003160 if (PCMfile.empty())
3161 return false;
3162
3163 // Clang module DWARF skeleton CUs abuse this for the path to the module.
3164 std::string PCMpath =
3165 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_comp_dir, "");
Adrian Prantl20937022015-09-23 17:11:10 +00003166 uint64_t DwoId = getDwoId(CUDie, Unit);
Adrian Prantle5162db2015-09-22 22:20:50 +00003167
Adrian Prantla112ef92015-09-23 17:35:52 +00003168 std::string Name =
3169 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_name, "");
3170 if (Name.empty()) {
3171 reportWarning("Anonymous module skeleton CU for " + PCMfile);
3172 return true;
3173 }
3174
Adrian Prantle5162db2015-09-22 22:20:50 +00003175 if (Options.Verbose) {
3176 outs().indent(Indent);
3177 outs() << "Found clang module reference " << PCMfile;
3178 }
3179
Adrian Prantl20937022015-09-23 17:11:10 +00003180 auto Cached = ClangModules.find(PCMfile);
3181 if (Cached != ClangModules.end()) {
3182 if (Cached->second != DwoId)
3183 reportWarning(Twine("hash mismatch: this object file was built against a "
3184 "different version of the module ") + PCMfile);
Adrian Prantle5162db2015-09-22 22:20:50 +00003185 if (Options.Verbose)
3186 outs() << " [cached].\n";
3187 return true;
3188 }
3189 if (Options.Verbose)
3190 outs() << " ...\n";
3191
3192 // Cyclic dependencies are disallowed by Clang, but we still
3193 // shouldn't run into an infinite loop, so mark it as processed now.
Adrian Prantl20937022015-09-23 17:11:10 +00003194 ClangModules.insert({PCMfile, DwoId});
Adrian Prantla112ef92015-09-23 17:35:52 +00003195 loadClangModule(PCMfile, PCMpath, Name, DwoId, ModuleMap, Indent + 2);
Adrian Prantle5162db2015-09-22 22:20:50 +00003196 return true;
3197}
3198
Frederic Risseb85c8f2015-07-24 06:41:11 +00003199ErrorOr<const object::ObjectFile &>
3200DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3201 const DebugMap &Map) {
3202 auto ErrOrObjs =
3203 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
Frederic Rissafeac302015-08-31 05:16:35 +00003204 if (std::error_code EC = ErrOrObjs.getError()) {
Frederic Risseb85c8f2015-07-24 06:41:11 +00003205 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
Frederic Rissafeac302015-08-31 05:16:35 +00003206 return EC;
3207 }
Frederic Risseb85c8f2015-07-24 06:41:11 +00003208 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3209 if (std::error_code EC = ErrOrObj.getError())
3210 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3211 return ErrOrObj;
3212}
3213
Adrian Prantle5162db2015-09-22 22:20:50 +00003214void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
Adrian Prantla112ef92015-09-23 17:35:52 +00003215 StringRef ModuleName, uint64_t DwoId,
3216 DebugMap &ModuleMap, unsigned Indent) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003217 SmallString<80> Path(Options.PrependPath);
3218 if (sys::path::is_relative(Filename))
3219 sys::path::append(Path, ModulePath, Filename);
3220 else
3221 sys::path::append(Path, Filename);
3222 BinaryHolder ObjHolder(Options.Verbose);
3223 auto &Obj =
3224 ModuleMap.addDebugMapObject(Path, sys::TimeValue::PosixZeroTime());
3225 auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
3226 if (!ErrOrObj) {
3227 ClangModules.erase(ClangModules.find(Filename));
3228 return;
3229 }
3230
Benjamin Kramer008f4be2015-09-23 10:38:59 +00003231 std::unique_ptr<CompileUnit> Unit;
Adrian Prantle5162db2015-09-22 22:20:50 +00003232
3233 // Setup access to the debug info.
3234 DWARFContextInMemory DwarfContext(*ErrOrObj);
3235 RelocationManager RelocMgr(*this);
3236 for (const auto &CU : DwarfContext.compile_units()) {
3237 auto *CUDie = CU->getUnitDIE(false);
3238 // Recursively get all modules imported by this one.
3239 if (!registerModuleReference(*CUDie, *CU, ModuleMap, Indent)) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003240 if (Unit) {
3241 errs() << Filename << ": Clang modules are expected to have exactly"
3242 << " 1 compile unit.\n";
3243 exitDsymutil(1);
3244 }
Adrian Prantl20937022015-09-23 17:11:10 +00003245 if (getDwoId(*CUDie, *CU) != DwoId)
3246 reportWarning(
3247 Twine("hash mismatch: this object file was built against a "
3248 "different version of the module ") + Filename);
3249
3250 // Add this module.
Adrian Prantla112ef92015-09-23 17:35:52 +00003251 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
3252 ModuleName);
Adrian Prantle5162db2015-09-22 22:20:50 +00003253 Unit->setHasInterestingContent();
Adrian Prantla112ef92015-09-23 17:35:52 +00003254 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3255 ODRContexts);
Adrian Prantle5162db2015-09-22 22:20:50 +00003256 // Keep everything.
3257 Unit->markEverythingAsKept();
3258 }
3259 }
3260 if (Options.Verbose) {
3261 outs().indent(Indent);
3262 outs() << "cloning .debug_info from " << Filename << "\n";
3263 }
3264
3265 DIECloner(*this, RelocMgr, DIEAlloc, MutableArrayRef<CompileUnit>(*Unit),
3266 Options)
3267 .cloneAllCompileUnits(DwarfContext);
3268}
3269
Adrian Prantl3565af42015-09-14 16:46:10 +00003270void DwarfLinker::DIECloner::cloneAllCompileUnits(
3271 DWARFContextInMemory &DwarfContext) {
3272 if (!Linker.Streamer)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003273 return;
3274
3275 for (auto &CurrentUnit : CompileUnits) {
3276 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Adrian Prantl3565af42015-09-14 16:46:10 +00003277 CurrentUnit.setStartOffset(Linker.OutputDebugInfoSize);
Adrian Prantl3abe18d2015-09-14 23:27:26 +00003278 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PC offset */,
3279 11 /* Unit Header size */, 0);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003280 CurrentUnit.setOutputUnitDIE(OutputDIE);
Adrian Prantl3565af42015-09-14 16:46:10 +00003281 Linker.OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3282 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003283 continue;
3284 // FIXME: for compatibility with the classic dsymutil, we emit
3285 // an empty line table for the unit, even if the unit doesn't
3286 // actually exist in the DIE tree.
Adrian Prantl3565af42015-09-14 16:46:10 +00003287 Linker.patchLineTableForUnit(CurrentUnit, DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003288 if (!OutputDIE)
3289 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003290 Linker.patchRangesForUnit(CurrentUnit, DwarfContext);
3291 Linker.Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3292 Linker.emitAcceleratorEntriesForUnit(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003293 }
3294
Adrian Prantl3565af42015-09-14 16:46:10 +00003295 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003296 return;
3297
3298 // Emit all the compile unit's debug information.
3299 for (auto &CurrentUnit : CompileUnits) {
Adrian Prantl3565af42015-09-14 16:46:10 +00003300 Linker.generateUnitRanges(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003301 CurrentUnit.fixupForwardReferences();
Adrian Prantl3565af42015-09-14 16:46:10 +00003302 Linker.Streamer->emitCompileUnitHeader(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003303 if (!CurrentUnit.getOutputUnitDIE())
3304 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003305 Linker.Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003306 }
3307}
3308
Frederic Rissd3455182015-01-28 18:27:01 +00003309bool DwarfLinker::link(const DebugMap &Map) {
3310
Frederic Rissc99ea202015-02-28 00:29:11 +00003311 if (!createStreamer(Map.getTriple(), OutputFilename))
3312 return false;
3313
Frederic Rissb8b43d52015-03-04 22:07:44 +00003314 // Size of the DIEs (and headers) generated for the linked output.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003315 OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003316 // A unique ID that identifies each compile unit.
Adrian Prantle5162db2015-09-22 22:20:50 +00003317 UnitID = 0;
3318 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3319
Frederic Rissd3455182015-01-28 18:27:01 +00003320 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003321 CurrentDebugObject = Obj.get();
3322
Frederic Rissb9818322015-02-28 00:29:07 +00003323 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003324 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003325 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3326 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003327 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003328
Frederic Riss1036e642015-02-13 23:18:22 +00003329 // Look for relocations that correspond to debug map entries.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003330 RelocationManager RelocMgr(*this);
3331 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003332 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003333 outs() << "No valid relocations found. Skipping.\n";
3334 continue;
3335 }
3336
Frederic Riss563cba62015-01-28 22:15:14 +00003337 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003338 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003339 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003340
Frederic Riss563cba62015-01-28 22:15:14 +00003341 // In a first phase, just read in the debug info and store the DIE
3342 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00003343 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003344 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003345 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003346 outs() << "Input compilation unit:";
3347 CUDie->dump(outs(), CU.get(), 0);
3348 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003349 if (!registerModuleReference(*CUDie, *CU, ModuleMap)) {
Adrian Prantla112ef92015-09-23 17:35:52 +00003350 Units.emplace_back(*CU, UnitID++, !Options.NoODR, "");
3351 analyzeContextInfo(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
3352 StringPool, ODRContexts);
Adrian Prantle5162db2015-09-22 22:20:50 +00003353 }
Frederic Rissd3455182015-01-28 18:27:01 +00003354 }
Frederic Riss563cba62015-01-28 22:15:14 +00003355
Frederic Riss84c09a52015-02-13 23:18:34 +00003356 // Then mark all the DIEs that need to be present in the linked
3357 // output and collect some information about them. Note that this
3358 // loop can not be merged with the previous one becaue cross-cu
3359 // references require the ParentIdx to be setup for every CU in
3360 // the object file before calling this.
3361 for (auto &CurrentUnit : Units)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003362 lookForDIEsToKeep(RelocMgr, *CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00003363 CurrentUnit, 0);
3364
Frederic Riss23e20e92015-03-07 01:25:09 +00003365 // The calls to applyValidRelocs inside cloneDIE will walk the
3366 // reloc array again (in the same way findValidRelocsInDebugInfo()
3367 // did). We need to reset the NextValidReloc index to the beginning.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003368 RelocMgr.resetValidRelocs();
3369 if (RelocMgr.hasValidRelocs())
Adrian Prantl3565af42015-09-14 16:46:10 +00003370 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3371 .cloneAllCompileUnits(DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003372 if (!Options.NoOutput && !Units.empty())
Frederic Riss5a642072015-06-05 23:06:11 +00003373 patchFrameInfoForObject(*Obj, DwarfContext,
3374 Units[0].getOrigUnit().getAddressByteSize());
3375
Frederic Riss563cba62015-01-28 22:15:14 +00003376 // Clean-up before starting working on the next object.
3377 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003378 }
3379
Frederic Rissb8b43d52015-03-04 22:07:44 +00003380 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003381 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003382 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003383 Streamer->emitStrings(StringPool);
3384 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003385
Frederic Riss24faade2015-09-02 16:49:13 +00003386 return Options.NoOutput ? true : Streamer->finish(Map);
Frederic Riss231f7142014-12-12 17:31:24 +00003387}
3388}
Frederic Rissd3455182015-01-28 18:27:01 +00003389
Frederic Riss30711fb2015-08-26 05:09:52 +00003390/// \brief Get the offset of string \p S in the string table. This
3391/// can insert a new element or return the offset of a preexisitng
3392/// one.
3393uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3394 if (S.empty() && !Strings.empty())
3395 return 0;
3396
3397 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3398 MapTy::iterator It;
3399 bool Inserted;
3400
3401 // A non-empty string can't be at offset 0, so if we have an entry
3402 // with a 0 offset, it must be a previously interned string.
3403 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3404 if (Inserted || It->getValue().first == 0) {
3405 // Set offset and chain at the end of the entries list.
3406 It->getValue().first = CurrentEndOffset;
3407 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3408 Last->getValue().second = &*It;
3409 Last = &*It;
3410 }
3411 return It->getValue().first;
3412}
3413
3414/// \brief Put \p S into the StringMap so that it gets permanent
3415/// storage, but do not actually link it in the chain of elements
3416/// that go into the output section. A latter call to
3417/// getStringOffset() with the same string will chain it though.
3418StringRef NonRelocatableStringpool::internString(StringRef S) {
3419 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3420 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3421 return InsertResult.first->getKey();
3422}
3423
Frederic Riss65e145c2015-08-26 05:09:55 +00003424void warn(const Twine &Warning, const Twine &Context) {
3425 errs() << Twine("while processing ") + Context + ":\n";
3426 errs() << Twine("warning: ") + Warning + "\n";
3427}
3428
3429bool error(const Twine &Error, const Twine &Context) {
3430 errs() << Twine("while processing ") + Context + ":\n";
3431 errs() << Twine("error: ") + Error + "\n";
3432 return false;
3433}
3434
Frederic Rissb9818322015-02-28 00:29:07 +00003435bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3436 const LinkOptions &Options) {
3437 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003438 return Linker.link(DM);
3439}
3440}
Frederic Riss231f7142014-12-12 17:31:24 +00003441}