blob: e8877a5da8949d2f3224bbf25ffeb5dea783f459 [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.
David Blaikie6196aa02015-11-18 00:34:10 +0000522 void emitAbbrevs(const std::vector<std::unique_ptr<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.
David Blaikie6196aa02015-11-18 00:34:10 +0000686void DwarfStreamer::emitAbbrevs(
687 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs) {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000688 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
689 Asm->emitDwarfAbbrevs(Abbrevs);
690}
691
692/// \brief Recursively emit the DIE tree rooted at \p Die.
693void DwarfStreamer::emitDIE(DIE &Die) {
694 MS->SwitchSection(MOFI->getDwarfInfoSection());
695 Asm->emitDwarfDIE(Die);
696}
697
Frederic Rissef648462015-03-06 17:56:30 +0000698/// \brief Emit the debug_str section stored in \p Pool.
699void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000700 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000701 for (auto *Entry = Pool.getFirstEntry(); Entry;
702 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000703 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000704 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
705}
706
Frederic Riss25440872015-03-13 23:30:31 +0000707/// \brief Emit the debug_range section contents for \p FuncRange by
708/// translating the original \p Entries. The debug_range section
709/// format is totally trivial, consisting just of pairs of address
710/// sized addresses describing the ranges.
711void DwarfStreamer::emitRangesEntries(
712 int64_t UnitPcOffset, uint64_t OrigLowPc,
713 FunctionIntervals::const_iterator FuncRange,
714 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
715 unsigned AddressSize) {
716 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
717
718 // Offset each range by the right amount.
Frederic Riss94546202015-08-31 05:09:32 +0000719 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
Frederic Riss25440872015-03-13 23:30:31 +0000720 for (const auto &Range : Entries) {
721 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
722 warn("unsupported base address selection operation",
723 "emitting debug_ranges");
724 break;
725 }
726 // Do not emit empty ranges.
727 if (Range.StartAddress == Range.EndAddress)
728 continue;
729
730 // All range entries should lie in the function range.
731 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
732 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
733 warn("inconsistent range data.", "emitting debug_ranges");
734 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
735 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
736 RangesSectionSize += 2 * AddressSize;
737 }
738
739 // Add the terminator entry.
740 MS->EmitIntValue(0, AddressSize);
741 MS->EmitIntValue(0, AddressSize);
742 RangesSectionSize += 2 * AddressSize;
743}
744
Frederic Riss563b1b02015-03-14 03:46:51 +0000745/// \brief Emit the debug_aranges contribution of a unit and
746/// if \p DoDebugRanges is true the debug_range contents for a
747/// compile_unit level DW_AT_ranges attribute (Which are basically the
748/// same thing with a different base address).
749/// Just aggregate all the ranges gathered inside that unit.
750void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
751 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000752 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
753 // Gather the ranges in a vector, so that we can simplify them. The
754 // IntervalMap will have coalesced the non-linked ranges, but here
755 // we want to coalesce the linked addresses.
756 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
757 const auto &FunctionRanges = Unit.getFunctionRanges();
758 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
759 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000760 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
761 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000762
763 // The object addresses where sorted, but again, the linked
764 // addresses might end up in a different order.
765 std::sort(Ranges.begin(), Ranges.end());
766
Frederic Riss563b1b02015-03-14 03:46:51 +0000767 if (!Ranges.empty()) {
768 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
769
Rafael Espindola9ab09232015-03-17 20:07:06 +0000770 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
771 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000772
773 unsigned HeaderSize =
774 sizeof(int32_t) + // Size of contents (w/o this field
775 sizeof(int16_t) + // DWARF ARange version number
776 sizeof(int32_t) + // Offset of CU in the .debug_info section
777 sizeof(int8_t) + // Pointer Size (in bytes)
778 sizeof(int8_t); // Segment Size (in bytes)
779
780 unsigned TupleSize = AddressSize * 2;
781 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
782
783 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000784 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000785 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
786 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
787 Asm->EmitInt8(AddressSize); // Address size
788 Asm->EmitInt8(0); // Segment size
789
Lang Hames9ff69c82015-04-24 19:11:51 +0000790 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000791
792 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
793 ++Range) {
794 uint64_t RangeStart = Range->first;
795 MS->EmitIntValue(RangeStart, AddressSize);
796 while ((Range + 1) != End && Range->second == (Range + 1)->first)
797 ++Range;
798 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
799 }
800
801 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000802 Asm->OutStreamer->EmitIntValue(0, AddressSize);
803 Asm->OutStreamer->EmitIntValue(0, AddressSize);
804 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000805 }
806
807 if (!DoDebugRanges)
808 return;
809
810 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
811 // Offset each range by the right amount.
812 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000813 // Emit coalesced ranges.
814 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000815 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000816 while (Range + 1 != End && Range->second == (Range + 1)->first)
817 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000818 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000819 RangesSectionSize += 2 * AddressSize;
820 }
821
822 // Add the terminator entry.
823 MS->EmitIntValue(0, AddressSize);
824 MS->EmitIntValue(0, AddressSize);
825 RangesSectionSize += 2 * AddressSize;
826}
827
Frederic Rissdfb97902015-03-14 15:49:07 +0000828/// \brief Emit location lists for \p Unit and update attribtues to
829/// point to the new entries.
830void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
831 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000832 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000833
834 if (Attributes.empty())
835 return;
836
837 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
838
839 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
840 const DWARFSection &InputSec = Dwarf.getLocSection();
841 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
842 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000843 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000844 int64_t UnitPcOffset = 0;
845 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
846 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
847 if (OrigLowPc != -1ULL)
848 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
849
850 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000851 uint32_t Offset = Attr.first.get();
852 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000853 // This is the quantity to add to the old location address to get
854 // the correct address for the new one.
855 int64_t LocPcOffset = Attr.second + UnitPcOffset;
856 while (Data.isValidOffset(Offset)) {
857 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
858 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
859 LocSectionSize += 2 * AddressSize;
860 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000861 Asm->OutStreamer->EmitIntValue(0, AddressSize);
862 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000863 break;
864 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000865 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
866 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000867 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000868 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000869 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000870 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000871 StringRef(InputSec.Data.substr(Offset, Length)));
872 Offset += Length;
873 LocSectionSize += Length + 2;
874 }
875 }
876}
877
Frederic Rissa5e14532015-08-07 15:14:13 +0000878void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
879 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000880 unsigned MinInstLength,
881 std::vector<DWARFDebugLine::Row> &Rows,
882 unsigned PointerSize) {
883 // Switch to the section where the table will be emitted into.
884 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000885 MCSymbol *LineStartSym = MC->createTempSymbol();
886 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000887
888 // The first 4 bytes is the total length of the information for this
889 // compilation unit (not including these 4 bytes for the length).
890 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000891 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000892 // Copy Prologue.
893 MS->EmitBytes(PrologueBytes);
894 LineSectionSize += PrologueBytes.size() + 4;
895
Frederic Rissc3820d02015-03-15 22:20:28 +0000896 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000897 raw_svector_ostream EncodingOS(EncodingBuffer);
898
899 if (Rows.empty()) {
900 // We only have the dummy entry, dsymutil emits an entry with a 0
901 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000902 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000903 MS->EmitBytes(EncodingOS.str());
904 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000905 MS->EmitLabel(LineEndSym);
906 return;
907 }
908
909 // Line table state machine fields
910 unsigned FileNum = 1;
911 unsigned LastLine = 1;
912 unsigned Column = 0;
913 unsigned IsStatement = 1;
914 unsigned Isa = 0;
915 uint64_t Address = -1ULL;
916
917 unsigned RowsSinceLastSequence = 0;
918
919 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
920 auto &Row = Rows[Idx];
921
922 int64_t AddressDelta;
923 if (Address == -1ULL) {
924 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
925 MS->EmitULEB128IntValue(PointerSize + 1);
926 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
927 MS->EmitIntValue(Row.Address, PointerSize);
928 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
929 AddressDelta = 0;
930 } else {
931 AddressDelta = (Row.Address - Address) / MinInstLength;
932 }
933
934 // FIXME: code copied and transfromed from
935 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
936 // this code, but the current compatibility requirement with
937 // classic dsymutil makes it hard. Revisit that once this
938 // requirement is dropped.
939
940 if (FileNum != Row.File) {
941 FileNum = Row.File;
942 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
943 MS->EmitULEB128IntValue(FileNum);
944 LineSectionSize += 1 + getULEB128Size(FileNum);
945 }
946 if (Column != Row.Column) {
947 Column = Row.Column;
948 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
949 MS->EmitULEB128IntValue(Column);
950 LineSectionSize += 1 + getULEB128Size(Column);
951 }
952
953 // FIXME: We should handle the discriminator here, but dsymutil
954 // doesn' consider it, thus ignore it for now.
955
956 if (Isa != Row.Isa) {
957 Isa = Row.Isa;
958 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
959 MS->EmitULEB128IntValue(Isa);
960 LineSectionSize += 1 + getULEB128Size(Isa);
961 }
962 if (IsStatement != Row.IsStmt) {
963 IsStatement = Row.IsStmt;
964 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
965 LineSectionSize += 1;
966 }
967 if (Row.BasicBlock) {
968 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
969 LineSectionSize += 1;
970 }
971
972 if (Row.PrologueEnd) {
973 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
974 LineSectionSize += 1;
975 }
976
977 if (Row.EpilogueBegin) {
978 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
979 LineSectionSize += 1;
980 }
981
982 int64_t LineDelta = int64_t(Row.Line) - LastLine;
983 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000984 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000985 MS->EmitBytes(EncodingOS.str());
986 LineSectionSize += EncodingBuffer.size();
987 EncodingBuffer.resize(0);
988 Address = Row.Address;
989 LastLine = Row.Line;
990 RowsSinceLastSequence++;
991 } else {
992 if (LineDelta) {
993 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
994 MS->EmitSLEB128IntValue(LineDelta);
995 LineSectionSize += 1 + getSLEB128Size(LineDelta);
996 }
997 if (AddressDelta) {
998 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
999 MS->EmitULEB128IntValue(AddressDelta);
1000 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1001 }
Frederic Rissa5e14532015-08-07 15:14:13 +00001002 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001003 MS->EmitBytes(EncodingOS.str());
1004 LineSectionSize += EncodingBuffer.size();
1005 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +00001006 Address = -1ULL;
1007 LastLine = FileNum = IsStatement = 1;
1008 RowsSinceLastSequence = Column = Isa = 0;
1009 }
1010 }
1011
1012 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +00001013 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001014 MS->EmitBytes(EncodingOS.str());
1015 LineSectionSize += EncodingBuffer.size();
1016 EncodingBuffer.resize(0);
1017 }
1018
1019 MS->EmitLabel(LineEndSym);
1020}
1021
Frederic Rissbce93ff2015-03-16 02:05:10 +00001022/// \brief Emit the pubnames or pubtypes section contribution for \p
1023/// Unit into \p Sec. The data is provided in \p Names.
1024void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001025 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001026 const std::vector<CompileUnit::AccelInfo> &Names) {
1027 if (Names.empty())
1028 return;
1029
1030 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001031 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001032 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1033 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001034
1035 bool HeaderEmitted = false;
1036 // Emit the pubnames for this compilation unit.
1037 for (const auto &Name : Names) {
1038 if (Name.SkipPubSection)
1039 continue;
1040
1041 if (!HeaderEmitted) {
1042 // Emit the header.
1043 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001044 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001045 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001046 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001047 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1048 HeaderEmitted = true;
1049 }
1050 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001051 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001052 StringRef(Name.Name.data(), Name.Name.size() + 1));
1053 }
1054
1055 if (!HeaderEmitted)
1056 return;
1057 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001058 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001059}
1060
1061/// \brief Emit .debug_pubnames for \p Unit.
1062void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1063 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1064 "names", Unit, Unit.getPubnames());
1065}
1066
1067/// \brief Emit .debug_pubtypes for \p Unit.
1068void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1069 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1070 "types", Unit, Unit.getPubtypes());
1071}
1072
Frederic Riss5a642072015-06-05 23:06:11 +00001073/// \brief Emit a CIE into the debug_frame section.
1074void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1075 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1076
1077 MS->EmitBytes(CIEBytes);
1078 FrameSectionSize += CIEBytes.size();
1079}
1080
1081/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1082/// contains the FDE data without the length, CIE offset and address
1083/// which will be replaced with the paramter values.
1084void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1085 uint32_t Address, StringRef FDEBytes) {
1086 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1087
1088 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1089 MS->EmitIntValue(CIEOffset, 4);
1090 MS->EmitIntValue(Address, AddrSize);
1091 MS->EmitBytes(FDEBytes);
1092 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1093}
1094
Frederic Rissd3455182015-01-28 18:27:01 +00001095/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001096///
1097/// The link of the dwarf information from the object files will be
1098/// driven by the selection of 'root DIEs', which are DIEs that
1099/// describe variables or functions that are present in the linked
1100/// binary (and thus have entries in the debug map). All the debug
1101/// information that will be linked (the DIEs, but also the line
1102/// tables, ranges, ...) is derived from that set of root DIEs.
1103///
1104/// The root DIEs are identified because they contain relocations that
1105/// correspond to a debug map entry at specific places (the low_pc for
1106/// a function, the location for a variable). These relocations are
1107/// called ValidRelocs in the DwarfLinker and are gathered as a very
1108/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001109class DwarfLinker {
1110public:
Frederic Rissb9818322015-02-28 00:29:07 +00001111 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1112 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001113 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001114
1115 /// \brief Link the contents of the DebugMap.
1116 bool link(const DebugMap &);
1117
Adrian Prantlc3021ee2015-09-22 18:50:51 +00001118 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1119 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1120
Frederic Rissd3455182015-01-28 18:27:01 +00001121private:
Frederic Riss563cba62015-01-28 22:15:14 +00001122 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001123 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001124
1125 /// \brief Called at the end of a debug object link.
1126 void endDebugObject();
1127
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001128 /// Keeps track of relocations.
1129 class RelocationManager {
1130 struct ValidReloc {
1131 uint32_t Offset;
1132 uint32_t Size;
1133 uint64_t Addend;
1134 const DebugMapObject::DebugMapEntry *Mapping;
Frederic Riss1036e642015-02-13 23:18:22 +00001135
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001136 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1137 const DebugMapObject::DebugMapEntry *Mapping)
1138 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
Frederic Riss1036e642015-02-13 23:18:22 +00001139
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001140 bool operator<(const ValidReloc &RHS) const {
1141 return Offset < RHS.Offset;
1142 }
1143 };
1144
1145 DwarfLinker &Linker;
1146
1147 /// \brief The valid relocations for the current DebugMapObject.
1148 /// This vector is sorted by relocation offset.
1149 std::vector<ValidReloc> ValidRelocs;
1150
1151 /// \brief Index into ValidRelocs of the next relocation to
1152 /// consider. As we walk the DIEs in acsending file offset and as
1153 /// ValidRelocs is sorted by file offset, keeping this index
1154 /// uptodate is all we have to do to have a cheap lookup during the
1155 /// root DIE selection and during DIE cloning.
1156 unsigned NextValidReloc;
1157
1158 public:
1159 RelocationManager(DwarfLinker &Linker)
1160 : Linker(Linker), NextValidReloc(0) {}
1161
1162 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1163 /// \brief Reset the NextValidReloc counter.
1164 void resetValidRelocs() { NextValidReloc = 0; }
1165
1166 /// \defgroup FindValidRelocations Translate debug map into a list
1167 /// of relevant relocations
1168 ///
1169 /// @{
1170 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1171 const DebugMapObject &DMO);
1172
1173 bool findValidRelocs(const object::SectionRef &Section,
1174 const object::ObjectFile &Obj,
1175 const DebugMapObject &DMO);
1176
1177 void findValidRelocsMachO(const object::SectionRef &Section,
1178 const object::MachOObjectFile &Obj,
1179 const DebugMapObject &DMO);
1180 /// @}
1181
1182 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1183 CompileUnit::DIEInfo &Info);
1184
1185 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1186 bool isLittleEndian);
Frederic Riss1036e642015-02-13 23:18:22 +00001187 };
1188
Frederic Riss84c09a52015-02-13 23:18:34 +00001189 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1190 ///
1191 /// @{
1192 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1193 /// keep. Store that information in \p CU's DIEInfo.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001194 void lookForDIEsToKeep(RelocationManager &RelocMgr,
1195 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001196 const DebugMapObject &DMO, CompileUnit &CU,
1197 unsigned Flags);
1198
Adrian Prantle5162db2015-09-22 22:20:50 +00001199 /// If this compile unit is really a skeleton CU that points to a
1200 /// clang module, register it in ClangModules and return true.
1201 ///
1202 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1203 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1204 /// hash.
1205 bool registerModuleReference(const DWARFDebugInfoEntryMinimal &CUDie,
1206 const DWARFUnit &Unit, DebugMap &ModuleMap,
1207 unsigned Indent = 0);
1208
1209 /// Recursively add the debug info in this clang module .pcm
1210 /// file (and all the modules imported by it in a bottom-up fashion)
1211 /// to Units.
Adrian Prantla112ef92015-09-23 17:35:52 +00001212 void loadClangModule(StringRef Filename, StringRef ModulePath,
1213 StringRef ModuleName, uint64_t DwoId,
Adrian Prantle5162db2015-09-22 22:20:50 +00001214 DebugMap &ModuleMap, unsigned Indent = 0);
1215
Frederic Riss84c09a52015-02-13 23:18:34 +00001216 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1217 enum TravesalFlags {
1218 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1219 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1220 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1221 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001222 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss29eedc72015-09-11 04:17:30 +00001223 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
Frederic Riss84c09a52015-02-13 23:18:34 +00001224 };
1225
1226 /// \brief Mark the passed DIE as well as all the ones it depends on
1227 /// as kept.
Adrian Prantl6ec47122015-09-22 15:31:14 +00001228 void keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001229 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001230 CompileUnit::DIEInfo &MyInfo,
1231 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001232 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001233
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001234 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1235 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001236 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1237 unsigned Flags);
1238
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001239 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1240 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001241 CompileUnit &Unit,
1242 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1243
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001244 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1245 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001246 CompileUnit &Unit,
1247 CompileUnit::DIEInfo &MyInfo,
1248 unsigned Flags);
1249
1250 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1251 CompileUnit::DIEInfo &Info);
1252 /// @}
1253
Frederic Rissb8b43d52015-03-04 22:07:44 +00001254 /// \defgroup Linking Methods used to link the debug information
1255 ///
1256 /// @{
Frederic Rissb8b43d52015-03-04 22:07:44 +00001257
Adrian Prantl3565af42015-09-14 16:46:10 +00001258 class DIECloner {
1259 DwarfLinker &Linker;
1260 RelocationManager &RelocMgr;
1261 /// Allocator used for all the DIEValue objects.
1262 BumpPtrAllocator &DIEAlloc;
1263 MutableArrayRef<CompileUnit> CompileUnits;
1264 LinkOptions Options;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001265
Adrian Prantl3565af42015-09-14 16:46:10 +00001266 public:
1267 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1268 BumpPtrAllocator &DIEAlloc,
1269 MutableArrayRef<CompileUnit> CompileUnits, LinkOptions &Options)
1270 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1271 CompileUnits(CompileUnits), Options(Options) {}
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001272
Adrian Prantl3565af42015-09-14 16:46:10 +00001273 /// Recursively clone \p InputDIE into an tree of DIE objects
1274 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1275 /// stripped out and addresses have been rewritten according to the
1276 /// debug map.
1277 ///
1278 /// \param OutOffset is the offset the cloned DIE in the output
1279 /// compile unit.
1280 /// \param PCOffset (while cloning a function scope) is the offset
1281 /// applied to the entry point of the function to get the linked address.
1282 ///
1283 /// \returns the root of the cloned tree or null if nothing was selected.
Adrian Prantl3abe18d2015-09-14 23:27:26 +00001284 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Adrian Prantl3565af42015-09-14 16:46:10 +00001285 int64_t PCOffset, uint32_t OutOffset, unsigned Flags);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001286
Adrian Prantl3565af42015-09-14 16:46:10 +00001287 /// Construct the output DIE tree by cloning the DIEs we
1288 /// chose to keep above. If there are no valid relocs, then there's
1289 /// nothing to clone/emit.
1290 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001291
Adrian Prantl3565af42015-09-14 16:46:10 +00001292 private:
1293 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
Frederic Rissbce93ff2015-03-16 02:05:10 +00001294
Adrian Prantl3565af42015-09-14 16:46:10 +00001295 /// Information gathered and exchanged between the various
1296 /// clone*Attributes helpers about the attributes of a particular DIE.
1297 struct AttributesInfo {
1298 const char *Name, *MangledName; ///< Names.
1299 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
Frederic Riss31da3242015-03-11 18:45:52 +00001300
Adrian Prantl3565af42015-09-14 16:46:10 +00001301 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1302 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1303 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
Frederic Rissbce93ff2015-03-16 02:05:10 +00001304
Adrian Prantl3565af42015-09-14 16:46:10 +00001305 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1306 bool IsDeclaration; ///< Is this DIE only a declaration?
1307
1308 AttributesInfo()
1309 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1310 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1311 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1312 };
1313
1314 /// Helper for cloneDIE.
1315 unsigned cloneAttribute(DIE &Die,
1316 const DWARFDebugInfoEntryMinimal &InputDIE,
1317 CompileUnit &U, const DWARFFormValue &Val,
1318 const AttributeSpec AttrSpec, unsigned AttrSize,
1319 AttributesInfo &AttrInfo);
1320
1321 /// Clone a string attribute described by \p AttrSpec and add
1322 /// it to \p Die.
1323 /// \returns the size of the new attribute.
1324 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1325 const DWARFFormValue &Val,
1326 const DWARFUnit &U);
1327
1328 /// Clone an attribute referencing another DIE and add
1329 /// it to \p Die.
1330 /// \returns the size of the new attribute.
1331 unsigned
1332 cloneDieReferenceAttribute(DIE &Die,
1333 const DWARFDebugInfoEntryMinimal &InputDIE,
1334 AttributeSpec AttrSpec, unsigned AttrSize,
1335 const DWARFFormValue &Val, CompileUnit &Unit);
1336
1337 /// Clone an attribute referencing another DIE and add
1338 /// it to \p Die.
1339 /// \returns the size of the new attribute.
1340 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1341 const DWARFFormValue &Val, unsigned AttrSize);
1342
1343 /// Clone an attribute referencing another DIE and add
1344 /// it to \p Die.
1345 /// \returns the size of the new attribute.
1346 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1347 const DWARFFormValue &Val,
1348 const CompileUnit &Unit,
1349 AttributesInfo &Info);
1350
1351 /// Clone a scalar attribute and add it to \p Die.
1352 /// \returns the size of the new attribute.
1353 unsigned cloneScalarAttribute(DIE &Die,
1354 const DWARFDebugInfoEntryMinimal &InputDIE,
1355 CompileUnit &U, AttributeSpec AttrSpec,
1356 const DWARFFormValue &Val, unsigned AttrSize,
1357 AttributesInfo &Info);
1358
1359 /// Get the potential name and mangled name for the entity
1360 /// described by \p Die and store them in \Info if they are not
1361 /// already there.
1362 /// \returns is a name was found.
1363 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1364 AttributesInfo &Info);
1365
1366 /// Create a copy of abbreviation Abbrev.
1367 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
Frederic Riss31da3242015-03-11 18:45:52 +00001368 };
1369
Frederic Rissb8b43d52015-03-04 22:07:44 +00001370 /// \brief Assign an abbreviation number to \p Abbrev
1371 void AssignAbbrev(DIEAbbrev &Abbrev);
1372
1373 /// \brief FoldingSet that uniques the abbreviations.
1374 FoldingSet<DIEAbbrev> AbbreviationsSet;
1375 /// \brief Storage for the unique Abbreviations.
1376 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1377 /// be changed to a vecot of unique_ptrs.
David Blaikie6196aa02015-11-18 00:34:10 +00001378 std::vector<std::unique_ptr<DIEAbbrev>> Abbreviations;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001379
Frederic Riss25440872015-03-13 23:30:31 +00001380 /// \brief Compute and emit debug_ranges section for \p Unit, and
1381 /// patch the attributes referencing it.
1382 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1383
1384 /// \brief Generate and emit the DW_AT_ranges attribute for a
1385 /// compile_unit if it had one.
1386 void generateUnitRanges(CompileUnit &Unit) const;
1387
Frederic Riss63786b02015-03-15 20:45:43 +00001388 /// \brief Extract the line tables fromt he original dwarf, extract
1389 /// the relevant parts according to the linked function ranges and
1390 /// emit the result in the debug_line section.
1391 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1392
Frederic Rissbce93ff2015-03-16 02:05:10 +00001393 /// \brief Emit the accelerator entries for \p Unit.
1394 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1395
Frederic Riss5a642072015-06-05 23:06:11 +00001396 /// \brief Patch the frame info for an object file and emit it.
1397 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1398 unsigned AddressSize);
1399
Frederic Rissb8b43d52015-03-04 22:07:44 +00001400 /// \brief DIELoc objects that need to be destructed (but not freed!).
1401 std::vector<DIELoc *> DIELocs;
1402 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1403 std::vector<DIEBlock *> DIEBlocks;
1404 /// \brief Allocator used for all the DIEValue objects.
1405 BumpPtrAllocator DIEAlloc;
1406 /// @}
1407
Frederic Riss1c650942015-07-21 22:41:43 +00001408 /// ODR Contexts for that link.
1409 DeclContextTree ODRContexts;
1410
Frederic Riss1b9da422015-02-13 23:18:29 +00001411 /// \defgroup Helpers Various helper methods.
1412 ///
1413 /// @{
Frederic Rissc99ea202015-02-28 00:29:11 +00001414 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001415
1416 /// \brief Attempt to load a debug object from disk.
1417 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1418 DebugMapObject &Obj,
1419 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001420 /// @}
1421
Frederic Rissd3455182015-01-28 18:27:01 +00001422 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001423 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001424 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001425 std::unique_ptr<DwarfStreamer> Streamer;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001426 uint64_t OutputDebugInfoSize;
Adrian Prantle5162db2015-09-22 22:20:50 +00001427 unsigned UnitID; ///< A unique ID that identifies each compile unit.
Frederic Riss563cba62015-01-28 22:15:14 +00001428
1429 /// The units of the current debug map object.
1430 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001431
Oleg Ranevskyy5f78c5c2015-10-23 17:10:44 +00001432 /// The debug map object currently under consideration.
Frederic Riss1b9da422015-02-13 23:18:29 +00001433 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001434
1435 /// \brief The Dwarf string pool
1436 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001437
1438 /// \brief This map is keyed by the entry PC of functions in that
1439 /// debug object and the associated value is a pair storing the
1440 /// corresponding end PC and the offset to apply to get the linked
1441 /// address.
1442 ///
1443 /// See startDebugObject() for a more complete description of its use.
1444 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001445
1446 /// \brief The CIEs that have been emitted in the output
1447 /// section. The actual CIE data serves a the key to this StringMap,
1448 /// this takes care of comparing the semantics of CIEs defined in
1449 /// different object files.
1450 StringMap<uint32_t> EmittedCIEs;
1451
1452 /// Offset of the last CIE that has been emitted in the output
1453 /// debug_frame section.
1454 uint32_t LastCIEOffset;
Adrian Prantle5162db2015-09-22 22:20:50 +00001455
Adrian Prantl20937022015-09-23 17:11:10 +00001456 /// Mapping the PCM filename to the DwoId.
1457 StringMap<uint64_t> ClangModules;
Frederic Rissd3455182015-01-28 18:27:01 +00001458};
1459
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001460/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1461/// CompileUnit object instead.
1462static CompileUnit *getUnitForOffset(MutableArrayRef<CompileUnit> Units,
1463 unsigned Offset) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001464 auto CU =
1465 std::upper_bound(Units.begin(), Units.end(), Offset,
1466 [](uint32_t LHS, const CompileUnit &RHS) {
1467 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1468 });
1469 return CU != Units.end() ? &*CU : nullptr;
1470}
1471
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001472/// Resolve the DIE attribute reference that has been
Frederic Riss1b9da422015-02-13 23:18:29 +00001473/// extracted in \p RefValue. The resulting DIE migh be in another
1474/// CompileUnit which is stored into \p ReferencedCU.
1475/// \returns null if resolving fails for any reason.
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001476static const DWARFDebugInfoEntryMinimal *resolveDIEReference(
1477 const DwarfLinker &Linker, MutableArrayRef<CompileUnit> Units,
Frederic Riss1c650942015-07-21 22:41:43 +00001478 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001479 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1480 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1481 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1482
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001483 if ((RefCU = getUnitForOffset(Units, RefOffset)))
Frederic Riss1b9da422015-02-13 23:18:29 +00001484 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1485 return RefDie;
1486
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001487 Linker.reportWarning("could not find referenced DIE", &Unit, &DIE);
Frederic Riss1b9da422015-02-13 23:18:29 +00001488 return nullptr;
1489}
1490
Frederic Riss1c650942015-07-21 22:41:43 +00001491/// \returns whether the passed \a Attr type might contain a DIE
1492/// reference suitable for ODR uniquing.
1493static bool isODRAttribute(uint16_t Attr) {
1494 switch (Attr) {
1495 default:
1496 return false;
1497 case dwarf::DW_AT_type:
1498 case dwarf::DW_AT_containing_type:
1499 case dwarf::DW_AT_specification:
1500 case dwarf::DW_AT_abstract_origin:
1501 case dwarf::DW_AT_import:
1502 return true;
1503 }
1504 llvm_unreachable("Improper attribute.");
1505}
1506
1507/// Set the last DIE/CU a context was seen in and, possibly invalidate
1508/// the context if it is ambiguous.
1509///
1510/// In the current implementation, we don't handle overloaded
1511/// functions well, because the argument types are not taken into
1512/// account when computing the DeclContext tree.
1513///
1514/// Some of this is mitigated byt using mangled names that do contain
1515/// the arguments types, but sometimes (eg. with function templates)
1516/// we don't have that. In that case, just do not unique anything that
1517/// refers to the contexts we are not able to distinguish.
1518///
1519/// If a context that is not a namespace appears twice in the same CU,
1520/// we know it is ambiguous. Make it invalid.
1521bool DeclContext::setLastSeenDIE(CompileUnit &U,
1522 const DWARFDebugInfoEntryMinimal *Die) {
1523 if (LastSeenCompileUnitID == U.getUniqueID()) {
1524 DWARFUnit &OrigUnit = U.getOrigUnit();
1525 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1526 U.getInfo(FirstIdx).Ctxt = nullptr;
1527 return false;
1528 }
1529
1530 LastSeenCompileUnitID = U.getUniqueID();
1531 LastSeenDIE = Die;
1532 return true;
1533}
1534
Frederic Riss1c650942015-07-21 22:41:43 +00001535PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1536 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
Adrian Prantl42562c32015-10-02 00:27:08 +00001537 NonRelocatableStringpool &StringPool, bool InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001538 unsigned Tag = DIE->getTag();
1539
1540 // FIXME: dsymutil-classic compat: We should bail out here if we
1541 // have a specification or an abstract_origin. We will get the
1542 // parent context wrong here.
1543
1544 switch (Tag) {
1545 default:
1546 // By default stop gathering child contexts.
1547 return PointerIntPair<DeclContext *, 1>(nullptr);
Adrian Prantla112ef92015-09-23 17:35:52 +00001548 case dwarf::DW_TAG_module:
1549 break;
Frederic Riss1c650942015-07-21 22:41:43 +00001550 case dwarf::DW_TAG_compile_unit:
Frederic Riss1c650942015-07-21 22:41:43 +00001551 return PointerIntPair<DeclContext *, 1>(&Context);
1552 case dwarf::DW_TAG_subprogram:
1553 // Do not unique anything inside CU local functions.
1554 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1555 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1556 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1557 dwarf::DW_AT_external, 0))
1558 return PointerIntPair<DeclContext *, 1>(nullptr);
1559 // Fallthrough
1560 case dwarf::DW_TAG_member:
1561 case dwarf::DW_TAG_namespace:
1562 case dwarf::DW_TAG_structure_type:
1563 case dwarf::DW_TAG_class_type:
1564 case dwarf::DW_TAG_union_type:
1565 case dwarf::DW_TAG_enumeration_type:
1566 case dwarf::DW_TAG_typedef:
1567 // Artificial things might be ambiguous, because they might be
1568 // created on demand. For example implicitely defined constructors
1569 // are ambiguous because of the way we identify contexts, and they
1570 // won't be generated everytime everywhere.
1571 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1572 dwarf::DW_AT_artificial, 0))
1573 return PointerIntPair<DeclContext *, 1>(nullptr);
1574 break;
1575 }
1576
1577 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1578 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1579 StringRef NameRef;
1580 StringRef ShortNameRef;
1581 StringRef FileRef;
1582
1583 if (Name)
1584 NameRef = StringPool.internString(Name);
1585 else if (Tag == dwarf::DW_TAG_namespace)
1586 // FIXME: For dsymutil-classic compatibility. I think uniquing
1587 // within anonymous namespaces is wrong. There is no ODR guarantee
1588 // there.
1589 NameRef = StringPool.internString("(anonymous namespace)");
1590
1591 if (ShortName && ShortName != Name)
1592 ShortNameRef = StringPool.internString(ShortName);
1593 else
1594 ShortNameRef = NameRef;
1595
1596 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1597 Tag != dwarf::DW_TAG_union_type &&
1598 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1599 return PointerIntPair<DeclContext *, 1>(nullptr);
1600
1601 std::string File;
1602 unsigned Line = 0;
Adrian Prantl42562c32015-10-02 00:27:08 +00001603 unsigned ByteSize = UINT32_MAX;
Frederic Riss1c650942015-07-21 22:41:43 +00001604
Adrian Prantl42562c32015-10-02 00:27:08 +00001605 if (!InClangModule) {
1606 // Gather some discriminating data about the DeclContext we will be
1607 // creating: File, line number and byte size. This shouldn't be
1608 // necessary, because the ODR is just about names, but given that we
1609 // do some approximations with overloaded functions and anonymous
1610 // namespaces, use these additional data points to make the process
1611 // safer. This is disabled for clang modules, because forward
1612 // declarations of module-defined types do not have a file and line.
1613 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1614 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1615 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1616 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1617 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1618 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1619 &U.getOrigUnit())) {
1620 // FIXME: dsymutil-classic compatibility. I'd rather not
1621 // unique anything in anonymous namespaces, but if we do, then
1622 // verify that the file and line correspond.
1623 if (!Name && Tag == dwarf::DW_TAG_namespace)
1624 FileNum = 1;
Frederic Riss1c650942015-07-21 22:41:43 +00001625
Adrian Prantl42562c32015-10-02 00:27:08 +00001626 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1627 // instead of "" would allow more uniquing, but for now, do
1628 // it this way to match dsymutil-classic.
1629 if (LT->getFileNameByIndex(
1630 FileNum, "",
1631 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1632 File)) {
1633 Line = DIE->getAttributeValueAsUnsignedConstant(
1634 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
Frederic Riss1c650942015-07-21 22:41:43 +00001635#ifdef HAVE_REALPATH
Adrian Prantl42562c32015-10-02 00:27:08 +00001636 // Cache the resolved paths, because calling realpath is expansive.
1637 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1638 File = ResolvedPath;
1639 } else {
1640 char RealPath[PATH_MAX + 1];
1641 RealPath[PATH_MAX] = 0;
1642 if (::realpath(File.c_str(), RealPath))
1643 File = RealPath;
1644 U.setResolvedPath(FileNum, File);
1645 }
Frederic Riss1c650942015-07-21 22:41:43 +00001646#endif
Adrian Prantl42562c32015-10-02 00:27:08 +00001647 FileRef = StringPool.internString(File);
1648 }
Frederic Riss1c650942015-07-21 22:41:43 +00001649 }
1650 }
1651 }
1652 }
1653
1654 if (!Line && NameRef.empty())
1655 return PointerIntPair<DeclContext *, 1>(nullptr);
1656
Frederic Riss1c650942015-07-21 22:41:43 +00001657 // We hash NameRef, which is the mangled name, in order to get most
Adrian Prantla112ef92015-09-23 17:35:52 +00001658 // overloaded functions resolve correctly.
1659 //
1660 // Strictly speaking, hashing the Tag is only necessary for a
1661 // DW_TAG_module, to prevent uniquing of a module and a namespace
1662 // with the same name.
1663 //
1664 // FIXME: dsymutil-classic won't unique the same type presented
1665 // once as a struct and once as a class. Using the Tag in the fully
1666 // qualified name hash to get the same effect.
Frederic Riss1c650942015-07-21 22:41:43 +00001667 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1668
1669 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1670 // use the filename.
1671 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1672 Hash = hash_combine(Hash, FileRef);
1673
1674 // Now look if this context already exists.
1675 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1676 auto ContextIter = Contexts.find(&Key);
1677
1678 if (ContextIter == Contexts.end()) {
1679 // The context wasn't found.
1680 bool Inserted;
1681 DeclContext *NewContext =
1682 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1683 Context, DIE, U.getUniqueID());
1684 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1685 assert(Inserted && "Failed to insert DeclContext");
1686 (void)Inserted;
1687 } else if (Tag != dwarf::DW_TAG_namespace &&
1688 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1689 // The context was found, but it is ambiguous with another context
1690 // in the same file. Mark it invalid.
1691 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1692 }
1693
1694 assert(ContextIter != Contexts.end());
1695 // FIXME: dsymutil-classic compatibility. Union types aren't
1696 // uniques, but their children might be.
1697 if ((Tag == dwarf::DW_TAG_subprogram &&
1698 Context.getTag() != dwarf::DW_TAG_structure_type &&
1699 Context.getTag() != dwarf::DW_TAG_class_type) ||
1700 (Tag == dwarf::DW_TAG_union_type))
1701 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1702
1703 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1704}
1705
Adrian Prantl3565af42015-09-14 16:46:10 +00001706bool DwarfLinker::DIECloner::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1707 DWARFUnit &U, AttributesInfo &Info) {
1708 // FIXME: a bit wasteful as the first getName might return the
Frederic Rissbce93ff2015-03-16 02:05:10 +00001709 // short name.
1710 if (!Info.MangledName &&
1711 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001712 Info.MangledNameOffset =
1713 Linker.StringPool.getStringOffset(Info.MangledName);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001714
1715 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001716 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001717
1718 return Info.Name || Info.MangledName;
1719}
1720
Frederic Riss1b9da422015-02-13 23:18:29 +00001721/// \brief Report a warning to the user, optionaly including
1722/// information about a specific \p DIE related to the warning.
1723void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001724 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001725 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001726 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001727 Context = CurrentDebugObject->getObjectFilename();
1728 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001729
Frederic Rissb9818322015-02-28 00:29:07 +00001730 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001731 return;
1732
1733 errs() << " in DIE:\n";
1734 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1735 6 /* Indent */);
1736}
1737
Frederic Rissc99ea202015-02-28 00:29:11 +00001738bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1739 if (Options.NoOutput)
1740 return true;
1741
Frederic Rissb52cf522015-02-28 00:42:37 +00001742 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001743 return Streamer->init(TheTriple, OutputFilename);
1744}
1745
Adrian Prantla112ef92015-09-23 17:35:52 +00001746/// Recursive helper to build the global DeclContext information and
1747/// gather the child->parent relationships in the original compile unit.
1748///
1749/// \return true when this DIE and all of its children are only
1750/// forward declarations to types defined in external clang modules
1751/// (i.e., forward declarations that are children of a DW_TAG_module).
1752static bool analyzeContextInfo(const DWARFDebugInfoEntryMinimal *DIE,
1753 unsigned ParentIdx, CompileUnit &CU,
1754 DeclContext *CurrentDeclContext,
1755 NonRelocatableStringpool &StringPool,
1756 DeclContextTree &Contexts,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001757 bool InImportedModule = false) {
Frederic Riss563cba62015-01-28 22:15:14 +00001758 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001759 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1760
Adrian Prantla112ef92015-09-23 17:35:52 +00001761 // Clang imposes an ODR on modules(!) regardless of the language:
1762 // "The module-id should consist of only a single identifier,
1763 // which provides the name of the module being defined. Each
1764 // module shall have a single definition."
1765 //
1766 // This does not extend to the types inside the modules:
1767 // "[I]n C, this implies that if two structs are defined in
1768 // different submodules with the same name, those two types are
1769 // distinct types (but may be compatible types if their
1770 // definitions match)."
1771 //
1772 // We treat non-C++ modules like namespaces for this reason.
Adrian Prantlf3e634b2015-09-24 16:10:14 +00001773 if (DIE->getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
Adrian Prantlea8a7242015-09-23 20:44:37 +00001774 DIE->getAttributeValueAsString(&CU.getOrigUnit(), dwarf::DW_AT_name,
1775 "") != CU.getClangModuleName()) {
1776 InImportedModule = true;
1777 }
Adrian Prantla112ef92015-09-23 17:35:52 +00001778
Frederic Riss1c650942015-07-21 22:41:43 +00001779 Info.ParentIdx = ParentIdx;
Adrian Prantl42562c32015-10-02 00:27:08 +00001780 bool InClangModule = CU.isClangModule() || InImportedModule;
1781 if (CU.hasODR() || InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001782 if (CurrentDeclContext) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001783 auto PtrInvalidPair = Contexts.getChildDeclContext(
1784 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +00001785 CurrentDeclContext = PtrInvalidPair.getPointer();
1786 Info.Ctxt =
1787 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1788 } else
1789 Info.Ctxt = CurrentDeclContext = nullptr;
1790 }
Frederic Riss563cba62015-01-28 22:15:14 +00001791
Adrian Prantlea8a7242015-09-23 20:44:37 +00001792 Info.Prune = InImportedModule;
Frederic Riss563cba62015-01-28 22:15:14 +00001793 if (DIE->hasChildren())
1794 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1795 Child = Child->getSibling())
Adrian Prantla112ef92015-09-23 17:35:52 +00001796 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001797 StringPool, Contexts, InImportedModule);
Adrian Prantla112ef92015-09-23 17:35:52 +00001798
1799 // Prune this DIE if it is either a forward declaration inside a
1800 // DW_TAG_module or a DW_TAG_module that contains nothing but
1801 // forward declarations.
1802 Info.Prune &= (DIE->getTag() == dwarf::DW_TAG_module) ||
1803 DIE->getAttributeValueAsUnsignedConstant(
1804 &CU.getOrigUnit(), dwarf::DW_AT_declaration, 0);
1805
Adrian Prantld2793a02015-10-05 23:11:20 +00001806 // Don't prune it if there is no definition for the DIE.
1807 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
1808
Adrian Prantla112ef92015-09-23 17:35:52 +00001809 return Info.Prune;
Frederic Riss563cba62015-01-28 22:15:14 +00001810}
1811
Frederic Riss84c09a52015-02-13 23:18:34 +00001812static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1813 switch (Tag) {
1814 default:
1815 return false;
1816 case dwarf::DW_TAG_subprogram:
1817 case dwarf::DW_TAG_lexical_block:
1818 case dwarf::DW_TAG_subroutine_type:
1819 case dwarf::DW_TAG_structure_type:
1820 case dwarf::DW_TAG_class_type:
1821 case dwarf::DW_TAG_union_type:
1822 return true;
1823 }
1824 llvm_unreachable("Invalid Tag");
1825}
1826
Frederic Riss1c650942015-07-21 22:41:43 +00001827static unsigned getRefAddrSize(const DWARFUnit &U) {
1828 if (U.getVersion() == 2)
1829 return U.getAddressByteSize();
1830 return 4;
1831}
1832
Frederic Riss63786b02015-03-15 20:45:43 +00001833void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001834 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss63786b02015-03-15 20:45:43 +00001835 // Iterate over the debug map entries and put all the ones that are
1836 // functions (because they have a size) into the Ranges map. This
1837 // map is very similar to the FunctionRanges that are stored in each
1838 // unit, with 2 notable differences:
1839 // - obviously this one is global, while the other ones are per-unit.
1840 // - this one contains not only the functions described in the DIE
1841 // tree, but also the ones that are only in the debug map.
1842 // The latter information is required to reproduce dsymutil's logic
1843 // while linking line tables. The cases where this information
1844 // matters look like bugs that need to be investigated, but for now
1845 // we need to reproduce dsymutil's behavior.
1846 // FIXME: Once we understood exactly if that information is needed,
1847 // maybe totally remove this (or try to use it to do a real
1848 // -gline-tables-only on Darwin.
1849 for (const auto &Entry : Obj.symbols()) {
1850 const auto &Mapping = Entry.getValue();
1851 if (Mapping.Size)
1852 Ranges[Mapping.ObjectAddress] = std::make_pair(
1853 Mapping.ObjectAddress + Mapping.Size,
1854 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1855 }
Frederic Riss563cba62015-01-28 22:15:14 +00001856}
1857
Frederic Riss1036e642015-02-13 23:18:22 +00001858void DwarfLinker::endDebugObject() {
1859 Units.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001860 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001861
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001862 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1863 (*I)->~DIEBlock();
1864 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1865 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001866
1867 DIEBlocks.clear();
1868 DIELocs.clear();
1869 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001870}
1871
1872/// \brief Iterate over the relocations of the given \p Section and
1873/// store the ones that correspond to debug map entries into the
1874/// ValidRelocs array.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001875void DwarfLinker::RelocationManager::
1876findValidRelocsMachO(const object::SectionRef &Section,
1877 const object::MachOObjectFile &Obj,
1878 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001879 StringRef Contents;
1880 Section.getContents(Contents);
1881 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1882
1883 for (const object::RelocationRef &Reloc : Section.relocations()) {
1884 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1885 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1886 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001887 uint64_t Offset64 = Reloc.getOffset();
1888 if ((RelocSize != 4 && RelocSize != 8)) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001889 Linker.reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001890 continue;
1891 }
1892 uint32_t Offset = Offset64;
1893 // Mach-o uses REL relocations, the addend is at the relocation offset.
1894 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1895
1896 auto Sym = Reloc.getSymbol();
1897 if (Sym != Obj.symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001898 ErrorOr<StringRef> SymbolName = Sym->getName();
1899 if (!SymbolName) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001900 Linker.reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001901 continue;
1902 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001903 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001904 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1905 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1906 // Do not store the addend. The addend was the address of the
1907 // symbol in the object file, the address in the binary that is
1908 // stored in the debug map doesn't need to be offseted.
1909 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1910 }
1911 }
1912}
1913
1914/// \brief Dispatch the valid relocation finding logic to the
1915/// appropriate handler depending on the object file format.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001916bool DwarfLinker::RelocationManager::findValidRelocs(
1917 const object::SectionRef &Section, const object::ObjectFile &Obj,
1918 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001919 // Dispatch to the right handler depending on the file type.
1920 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1921 findValidRelocsMachO(Section, *MachOObj, DMO);
1922 else
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001923 Linker.reportWarning(Twine("unsupported object file type: ") +
1924 Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001925
1926 if (ValidRelocs.empty())
1927 return false;
1928
1929 // Sort the relocations by offset. We will walk the DIEs linearly in
1930 // the file, this allows us to just keep an index in the relocation
1931 // array that we advance during our walk, rather than resorting to
1932 // some associative container. See DwarfLinker::NextValidReloc.
1933 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1934 return true;
1935}
1936
1937/// \brief Look for relocations in the debug_info section that match
1938/// entries in the debug map. These relocations will drive the Dwarf
1939/// link by indicating which DIEs refer to symbols present in the
1940/// linked binary.
1941/// \returns wether there are any valid relocations in the debug info.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001942bool DwarfLinker::RelocationManager::
1943findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1944 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001945 // Find the debug_info section.
1946 for (const object::SectionRef &Section : Obj.sections()) {
1947 StringRef SectionName;
1948 Section.getName(SectionName);
1949 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1950 if (SectionName != "debug_info")
1951 continue;
1952 return findValidRelocs(Section, Obj, DMO);
1953 }
1954 return false;
1955}
Frederic Riss563cba62015-01-28 22:15:14 +00001956
Frederic Riss84c09a52015-02-13 23:18:34 +00001957/// \brief Checks that there is a relocation against an actual debug
1958/// map entry between \p StartOffset and \p NextOffset.
1959///
1960/// This function must be called with offsets in strictly ascending
1961/// order because it never looks back at relocations it already 'went past'.
1962/// \returns true and sets Info.InDebugMap if it is the case.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001963bool DwarfLinker::RelocationManager::
1964hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1965 CompileUnit::DIEInfo &Info) {
Frederic Riss84c09a52015-02-13 23:18:34 +00001966 assert(NextValidReloc == 0 ||
1967 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1968 if (NextValidReloc >= ValidRelocs.size())
1969 return false;
1970
1971 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1972
1973 // We might need to skip some relocs that we didn't consider. For
1974 // example the high_pc of a discarded DIE might contain a reloc that
1975 // is in the list because it actually corresponds to the start of a
1976 // function that is in the debug map.
1977 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1978 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1979
1980 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1981 return false;
1982
1983 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001984 const auto &Mapping = ValidReloc.Mapping->getValue();
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001985 if (Linker.Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001986 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1987 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001988 uint64_t(Mapping.ObjectAddress),
1989 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001990
Frederic Rissf37964c2015-06-05 20:27:07 +00001991 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1992 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001993 Info.InDebugMap = true;
1994 return true;
1995}
1996
1997/// \brief Get the starting and ending (exclusive) offset for the
1998/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1999/// supposed to point to the position of the first attribute described
2000/// by \p Abbrev.
2001/// \return [StartOffset, EndOffset) as a pair.
2002static std::pair<uint32_t, uint32_t>
2003getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
2004 unsigned Offset, const DWARFUnit &Unit) {
2005 DataExtractor Data = Unit.getDebugInfoExtractor();
2006
2007 for (unsigned i = 0; i < Idx; ++i)
2008 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
2009
2010 uint32_t End = Offset;
2011 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
2012
2013 return std::make_pair(Offset, End);
2014}
2015
2016/// \brief Check if a variable describing DIE should be kept.
2017/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002018unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
2019 const DWARFDebugInfoEntryMinimal &DIE,
2020 CompileUnit &Unit,
2021 CompileUnit::DIEInfo &MyInfo,
2022 unsigned Flags) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002023 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2024
2025 // Global variables with constant value can always be kept.
2026 if (!(Flags & TF_InFunctionScope) &&
2027 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
2028 MyInfo.InDebugMap = true;
2029 return Flags | TF_Keep;
2030 }
2031
2032 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
2033 if (LocationIdx == -1U)
2034 return Flags;
2035
2036 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2037 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2038 uint32_t LocationOffset, LocationEndOffset;
2039 std::tie(LocationOffset, LocationEndOffset) =
2040 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
2041
2042 // See if there is a relocation to a valid debug map entry inside
2043 // this variable's location. The order is important here. We want to
2044 // always check in the variable has a valid relocation, so that the
2045 // DIEInfo is filled. However, we don't want a static variable in a
2046 // function to force us to keep the enclosing function.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002047 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
Frederic Riss84c09a52015-02-13 23:18:34 +00002048 (Flags & TF_InFunctionScope))
2049 return Flags;
2050
Frederic Rissb9818322015-02-28 00:29:07 +00002051 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002052 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2053
2054 return Flags | TF_Keep;
2055}
2056
2057/// \brief Check if a function describing DIE should be kept.
2058/// \returns updated TraversalFlags.
2059unsigned DwarfLinker::shouldKeepSubprogramDIE(
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002060 RelocationManager &RelocMgr,
Frederic Riss84c09a52015-02-13 23:18:34 +00002061 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2062 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2063 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2064
2065 Flags |= TF_InFunctionScope;
2066
2067 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2068 if (LowPcIdx == -1U)
2069 return Flags;
2070
2071 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2072 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2073 uint32_t LowPcOffset, LowPcEndOffset;
2074 std::tie(LowPcOffset, LowPcEndOffset) =
2075 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2076
2077 uint64_t LowPc =
2078 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2079 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2080 if (LowPc == -1ULL ||
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002081 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
Frederic Riss84c09a52015-02-13 23:18:34 +00002082 return Flags;
2083
Frederic Rissb9818322015-02-28 00:29:07 +00002084 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002085 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2086
Frederic Riss1af75f72015-03-12 18:45:10 +00002087 Flags |= TF_Keep;
2088
2089 DWARFFormValue HighPcValue;
2090 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2091 reportWarning("Function without high_pc. Range will be discarded.\n",
2092 &OrigUnit, &DIE);
2093 return Flags;
2094 }
2095
2096 uint64_t HighPc;
2097 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2098 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2099 } else {
2100 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2101 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2102 }
2103
Frederic Riss63786b02015-03-15 20:45:43 +00002104 // Replace the debug map range with a more accurate one.
2105 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002106 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2107 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002108}
2109
2110/// \brief Check if a DIE should be kept.
2111/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002112unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2113 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00002114 CompileUnit &Unit,
2115 CompileUnit::DIEInfo &MyInfo,
2116 unsigned Flags) {
2117 switch (DIE.getTag()) {
2118 case dwarf::DW_TAG_constant:
2119 case dwarf::DW_TAG_variable:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002120 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002121 case dwarf::DW_TAG_subprogram:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002122 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002123 case dwarf::DW_TAG_module:
2124 case dwarf::DW_TAG_imported_module:
2125 case dwarf::DW_TAG_imported_declaration:
2126 case dwarf::DW_TAG_imported_unit:
2127 // We always want to keep these.
2128 return Flags | TF_Keep;
2129 }
2130
2131 return Flags;
2132}
2133
Frederic Riss84c09a52015-02-13 23:18:34 +00002134/// \brief Mark the passed DIE as well as all the ones it depends on
2135/// as kept.
2136///
2137/// This function is called by lookForDIEsToKeep on DIEs that are
2138/// newly discovered to be needed in the link. It recursively calls
2139/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2140/// TraversalFlags to inform it that it's not doing the primary DIE
2141/// tree walk.
Adrian Prantl6ec47122015-09-22 15:31:14 +00002142void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002143 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002144 CompileUnit::DIEInfo &MyInfo,
2145 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002146 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002147 const DWARFUnit &Unit = CU.getOrigUnit();
2148 MyInfo.Keep = true;
2149
2150 // First mark all the parent chain as kept.
2151 unsigned AncestorIdx = MyInfo.ParentIdx;
2152 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002153 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002154 lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002155 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002156 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2157 }
2158
2159 // Then we need to mark all the DIEs referenced by this DIE's
2160 // attributes as kept.
2161 DataExtractor Data = Unit.getDebugInfoExtractor();
Frederic Riss36c3cb82015-09-11 04:17:25 +00002162 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2163 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
Frederic Riss84c09a52015-02-13 23:18:34 +00002164
2165 // Mark all DIEs referenced through atttributes as kept.
2166 for (const auto &AttrSpec : Abbrev->attributes()) {
2167 DWARFFormValue Val(AttrSpec.Form);
2168
2169 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2170 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2171 continue;
2172 }
2173
2174 Val.extractValue(Data, &Offset, &Unit);
2175 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002176 if (const auto *RefDIE =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002177 resolveDIEReference(*this, MutableArrayRef<CompileUnit>(Units), Val,
2178 Unit, Die, ReferencedCU)) {
Frederic Riss1c650942015-07-21 22:41:43 +00002179 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2180 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2181 // If the referenced DIE has a DeclContext that has already been
2182 // emitted, then do not keep the one in this CU. We'll link to
2183 // the canonical DIE in cloneDieReferenceAttribute.
2184 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2185 // be necessary and could be advantageously replaced by
2186 // ReferencedCU->hasODR() && CU.hasODR().
2187 // FIXME: compatibility with dsymutil-classic. There is no
2188 // reason not to unique ref_addr references.
2189 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2190 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2191 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2192 continue;
2193
Adrian Prantle39475d2015-11-10 21:31:05 +00002194 // Keep a module forward declaration if there is no definition.
2195 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
2196 Info.Ctxt->getCanonicalDIEOffset()))
2197 Info.Prune = false;
2198
Frederic Riss1c650942015-07-21 22:41:43 +00002199 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002200 lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002201 TF_Keep | TF_DependencyWalk | ODRFlag);
2202 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002203 }
2204}
2205
2206/// \brief Recursively walk the \p DIE tree and look for DIEs to
2207/// keep. Store that information in \p CU's DIEInfo.
2208///
2209/// This function is the entry point of the DIE selection
2210/// algorithm. It is expected to walk the DIE tree in file order and
2211/// (though the mediation of its helper) call hasValidRelocation() on
2212/// each DIE that might be a 'root DIE' (See DwarfLinker class
2213/// comment).
2214/// While walking the dependencies of root DIEs, this function is
2215/// also called, but during these dependency walks the file order is
2216/// not respected. The TF_DependencyWalk flag tells us which kind of
2217/// traversal we are currently doing.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002218void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2219 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002220 const DebugMapObject &DMO, CompileUnit &CU,
2221 unsigned Flags) {
Frederic Riss36c3cb82015-09-11 04:17:25 +00002222 unsigned Idx = CU.getOrigUnit().getDIEIndex(&Die);
Frederic Riss84c09a52015-02-13 23:18:34 +00002223 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2224 bool AlreadyKept = MyInfo.Keep;
Adrian Prantla112ef92015-09-23 17:35:52 +00002225 if (MyInfo.Prune)
2226 return;
Frederic Riss84c09a52015-02-13 23:18:34 +00002227
2228 // If the Keep flag is set, we are marking a required DIE's
2229 // dependencies. If our target is already marked as kept, we're all
2230 // set.
2231 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2232 return;
2233
Adrian Prantl6ec47122015-09-22 15:31:14 +00002234 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
Frederic Riss84c09a52015-02-13 23:18:34 +00002235 // because it would screw up the relocation finding logic.
2236 if (!(Flags & TF_DependencyWalk))
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002237 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002238
2239 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002240 if (!AlreadyKept && (Flags & TF_Keep)) {
2241 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
Adrian Prantl6ec47122015-09-22 15:31:14 +00002242 keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
Frederic Riss1c650942015-07-21 22:41:43 +00002243 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002244 // The TF_ParentWalk flag tells us that we are currently walking up
2245 // the parent chain of a required DIE, and we don't want to mark all
2246 // the children of the parents as kept (consider for example a
2247 // DW_TAG_namespace node in the parent chain). There are however a
2248 // set of DIE types for which we want to ignore that directive and still
2249 // walk their children.
Frederic Riss36c3cb82015-09-11 04:17:25 +00002250 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
Frederic Riss84c09a52015-02-13 23:18:34 +00002251 Flags &= ~TF_ParentWalk;
2252
Frederic Riss36c3cb82015-09-11 04:17:25 +00002253 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
Frederic Riss84c09a52015-02-13 23:18:34 +00002254 return;
2255
Frederic Riss36c3cb82015-09-11 04:17:25 +00002256 for (auto *Child = Die.getFirstChild(); Child && !Child->isNULL();
Frederic Riss84c09a52015-02-13 23:18:34 +00002257 Child = Child->getSibling())
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002258 lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002259}
2260
Frederic Rissb8b43d52015-03-04 22:07:44 +00002261/// \brief Assign an abbreviation numer to \p Abbrev.
2262///
2263/// Our DIEs get freed after every DebugMapObject has been processed,
2264/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2265/// the instances hold by the DIEs. When we encounter an abbreviation
2266/// that we don't know, we create a permanent copy of it.
2267void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2268 // Check the set for priors.
2269 FoldingSetNodeID ID;
2270 Abbrev.Profile(ID);
2271 void *InsertToken;
2272 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2273
2274 // If it's newly added.
2275 if (InSet) {
2276 // Assign existing abbreviation number.
2277 Abbrev.setNumber(InSet->getNumber());
2278 } else {
2279 // Add to abbreviation list.
2280 Abbreviations.push_back(
David Blaikie6196aa02015-11-18 00:34:10 +00002281 llvm::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002282 for (const auto &Attr : Abbrev.getData())
2283 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
David Blaikie6196aa02015-11-18 00:34:10 +00002284 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002285 // Assign the unique abbreviation number.
2286 Abbrev.setNumber(Abbreviations.size());
2287 Abbreviations.back()->setNumber(Abbreviations.size());
2288 }
2289}
2290
Adrian Prantl3565af42015-09-14 16:46:10 +00002291unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2292 AttributeSpec AttrSpec,
2293 const DWARFFormValue &Val,
2294 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002295 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002296 const char *String = *Val.getAsCString(&U);
Adrian Prantl3565af42015-09-14 16:46:10 +00002297 unsigned Offset = Linker.StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002298 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002299 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002300 return 4;
2301}
2302
Adrian Prantl3565af42015-09-14 16:46:10 +00002303unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
Frederic Riss9833de62015-03-06 23:22:53 +00002304 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2305 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002306 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002307 const DWARFUnit &U = Unit.getOrigUnit();
2308 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002309 DIE *NewRefDie = nullptr;
2310 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002311 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002312
Frederic Riss1c650942015-07-21 22:41:43 +00002313 const DWARFDebugInfoEntryMinimal *RefDie =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002314 resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE, RefUnit);
Frederic Riss1c650942015-07-21 22:41:43 +00002315
2316 // If the referenced DIE is not found, drop the attribute.
2317 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002318 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002319
2320 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2321 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002322
2323 // If we already have emitted an equivalent DeclContext, just point
2324 // at it.
2325 if (isODRAttribute(AttrSpec.Attr)) {
2326 Ctxt = RefInfo.Ctxt;
2327 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2328 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2329 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2330 dwarf::DW_FORM_ref_addr, Attr);
2331 return getRefAddrSize(U);
2332 }
2333 }
2334
Frederic Riss9833de62015-03-06 23:22:53 +00002335 if (!RefInfo.Clone) {
2336 assert(Ref > InputDIE.getOffset());
2337 // We haven't cloned this DIE yet. Just create an empty one and
2338 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002339 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002340 }
2341 NewRefDie = RefInfo.Clone;
2342
Frederic Riss1c650942015-07-21 22:41:43 +00002343 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2344 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002345 // We cannot currently rely on a DIEEntry to emit ref_addr
2346 // references, because the implementation calls back to DwarfDebug
2347 // to find the unit offset. (We don't have a DwarfDebug)
2348 // FIXME: we should be able to design DIEEntry reliance on
2349 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002350 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002351 if (Ref < InputDIE.getOffset()) {
2352 // We must have already cloned that DIE.
2353 uint32_t NewRefOffset =
2354 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002355 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002356 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2357 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002358 } else {
2359 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002360 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002361 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002362 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002363 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2364 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002365 }
Frederic Riss1c650942015-07-21 22:41:43 +00002366 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002367 }
2368
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002369 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2370 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002371 return AttrSize;
2372}
2373
Adrian Prantl3565af42015-09-14 16:46:10 +00002374unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2375 AttributeSpec AttrSpec,
2376 const DWARFFormValue &Val,
2377 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002378 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002379 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002380 DIELoc *Loc = nullptr;
2381 DIEBlock *Block = nullptr;
2382 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002383 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002384 Loc = new (DIEAlloc) DIELoc;
Adrian Prantl3565af42015-09-14 16:46:10 +00002385 Linker.DIELocs.push_back(Loc);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002386 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002387 Block = new (DIEAlloc) DIEBlock;
Adrian Prantl3565af42015-09-14 16:46:10 +00002388 Linker.DIEBlocks.push_back(Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002389 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002390 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2391 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002392
2393 if (Loc)
2394 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2395 dwarf::Form(AttrSpec.Form), Loc);
2396 else
2397 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2398 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002399 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2400 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002401 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2402 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002403 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2404 // the DIE class, this if could be replaced by
2405 // Attr->setSize(Bytes.size()).
Adrian Prantl3565af42015-09-14 16:46:10 +00002406 if (Linker.Streamer) {
2407 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002408 if (Loc)
Adrian Prantl3565af42015-09-14 16:46:10 +00002409 Loc->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002410 else
Adrian Prantl3565af42015-09-14 16:46:10 +00002411 Block->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002412 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002413 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002414 return AttrSize;
2415}
2416
Adrian Prantl3565af42015-09-14 16:46:10 +00002417unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2418 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2419 const CompileUnit &Unit, AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002420 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002421 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2422 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2423 Die.getTag() == dwarf::DW_TAG_lexical_block)
Frederic Riss7b5563a2015-08-31 01:43:14 +00002424 // The low_pc of a block or inline subroutine might get
2425 // relocated because it happens to match the low_pc of the
2426 // enclosing subprogram. To prevent issues with that, always use
2427 // the low_pc from the input DIE if relocations have been applied.
2428 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2429 Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002430 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2431 Addr = Unit.getLowPc();
2432 if (Addr == UINT64_MAX)
2433 return 0;
2434 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002435 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002436 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002437 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2438 if (uint64_t HighPc = Unit.getHighPc())
2439 Addr = HighPc;
2440 else
2441 return 0;
2442 } else
2443 // If we have a high_pc recorded for the input DIE, use
2444 // it. Otherwise (when no relocations where applied) just use the
2445 // one we just decoded.
2446 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002447 }
2448
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002449 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002450 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002451 return Unit.getOrigUnit().getAddressByteSize();
2452}
2453
Adrian Prantl3565af42015-09-14 16:46:10 +00002454unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002455 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002456 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002457 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002458 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002459 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2460 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2461 if (Unit.getLowPc() == -1ULL)
2462 return 0;
2463 // Dwarf >= 4 high_pc is an size, not an address.
2464 Value = Unit.getHighPc() - Unit.getLowPc();
2465 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002466 Value = *Val.getAsSectionOffset();
2467 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2468 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002469 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2470 Value = *OptionalValue;
2471 else {
Adrian Prantl3565af42015-09-14 16:46:10 +00002472 Linker.reportWarning(
2473 "Unsupported scalar attribute form. Dropping attribute.",
2474 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002475 return 0;
2476 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002477 PatchLocation Patch =
2478 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2479 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002480 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002481 Unit.noteRangeAttribute(Die, Patch);
Frederic Riss29eedc72015-09-11 04:17:30 +00002482
Frederic Rissdfb97902015-03-14 15:49:07 +00002483 // A more generic way to check for location attributes would be
2484 // nice, but it's very unlikely that any other attribute needs a
2485 // location list.
2486 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2487 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002488 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002489 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2490 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002491
Frederic Rissb8b43d52015-03-04 22:07:44 +00002492 return AttrSize;
2493}
2494
2495/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2496/// value \p Val, and add it to \p Die.
2497/// \returns the size of the cloned attribute.
Adrian Prantl3565af42015-09-14 16:46:10 +00002498unsigned DwarfLinker::DIECloner::cloneAttribute(
2499 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2500 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2501 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002502 const DWARFUnit &U = Unit.getOrigUnit();
2503
2504 switch (AttrSpec.Form) {
2505 case dwarf::DW_FORM_strp:
2506 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002507 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002508 case dwarf::DW_FORM_ref_addr:
2509 case dwarf::DW_FORM_ref1:
2510 case dwarf::DW_FORM_ref2:
2511 case dwarf::DW_FORM_ref4:
2512 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002513 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002514 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002515 case dwarf::DW_FORM_block:
2516 case dwarf::DW_FORM_block1:
2517 case dwarf::DW_FORM_block2:
2518 case dwarf::DW_FORM_block4:
2519 case dwarf::DW_FORM_exprloc:
2520 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2521 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002522 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002523 case dwarf::DW_FORM_data1:
2524 case dwarf::DW_FORM_data2:
2525 case dwarf::DW_FORM_data4:
2526 case dwarf::DW_FORM_data8:
2527 case dwarf::DW_FORM_udata:
2528 case dwarf::DW_FORM_sdata:
2529 case dwarf::DW_FORM_sec_offset:
2530 case dwarf::DW_FORM_flag:
2531 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002532 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2533 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002534 default:
Adrian Prantl3565af42015-09-14 16:46:10 +00002535 Linker.reportWarning(
2536 "Unsupported attribute form in cloneAttribute. Dropping.", &U,
2537 &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002538 }
2539
2540 return 0;
2541}
2542
Frederic Riss23e20e92015-03-07 01:25:09 +00002543/// \brief Apply the valid relocations found by findValidRelocs() to
2544/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2545/// in the debug_info section.
2546///
2547/// Like for findValidRelocs(), this function must be called with
2548/// monotonic \p BaseOffset values.
2549///
2550/// \returns wether any reloc has been applied.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002551bool DwarfLinker::RelocationManager::
2552applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2553 bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002554 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002555 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2556 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002557 if (NextValidReloc >= ValidRelocs.size())
2558 return false;
2559
2560 // Skip relocs that haven't been applied.
2561 while (NextValidReloc < ValidRelocs.size() &&
2562 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2563 ++NextValidReloc;
2564
2565 bool Applied = false;
2566 uint64_t EndOffset = BaseOffset + Data.size();
2567 while (NextValidReloc < ValidRelocs.size() &&
2568 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2569 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2570 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2571 assert(ValidReloc.Offset - BaseOffset < Data.size());
2572 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2573 char Buf[8];
2574 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2575 Value += ValidReloc.Addend;
2576 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2577 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2578 Buf[i] = uint8_t(Value >> (Index * 8));
2579 }
2580 assert(ValidReloc.Size <= sizeof(Buf));
2581 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2582 Applied = true;
2583 }
2584
2585 return Applied;
2586}
2587
Frederic Rissbce93ff2015-03-16 02:05:10 +00002588static bool isTypeTag(uint16_t Tag) {
2589 switch (Tag) {
2590 case dwarf::DW_TAG_array_type:
2591 case dwarf::DW_TAG_class_type:
2592 case dwarf::DW_TAG_enumeration_type:
2593 case dwarf::DW_TAG_pointer_type:
2594 case dwarf::DW_TAG_reference_type:
2595 case dwarf::DW_TAG_string_type:
2596 case dwarf::DW_TAG_structure_type:
2597 case dwarf::DW_TAG_subroutine_type:
2598 case dwarf::DW_TAG_typedef:
2599 case dwarf::DW_TAG_union_type:
2600 case dwarf::DW_TAG_ptr_to_member_type:
2601 case dwarf::DW_TAG_set_type:
2602 case dwarf::DW_TAG_subrange_type:
2603 case dwarf::DW_TAG_base_type:
2604 case dwarf::DW_TAG_const_type:
2605 case dwarf::DW_TAG_constant:
2606 case dwarf::DW_TAG_file_type:
2607 case dwarf::DW_TAG_namelist:
2608 case dwarf::DW_TAG_packed_type:
2609 case dwarf::DW_TAG_volatile_type:
2610 case dwarf::DW_TAG_restrict_type:
2611 case dwarf::DW_TAG_interface_type:
2612 case dwarf::DW_TAG_unspecified_type:
2613 case dwarf::DW_TAG_shared_type:
2614 return true;
2615 default:
2616 break;
2617 }
2618 return false;
2619}
2620
Frederic Riss29eedc72015-09-11 04:17:30 +00002621static bool
2622shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2623 uint16_t Tag, bool InDebugMap, bool SkipPC,
2624 bool InFunctionScope) {
2625 switch (AttrSpec.Attr) {
2626 default:
2627 return false;
2628 case dwarf::DW_AT_low_pc:
2629 case dwarf::DW_AT_high_pc:
2630 case dwarf::DW_AT_ranges:
2631 return SkipPC;
2632 case dwarf::DW_AT_location:
2633 case dwarf::DW_AT_frame_base:
2634 // FIXME: for some reason dsymutil-classic keeps the location
2635 // attributes when they are of block type (ie. not location
2636 // lists). This is totally wrong for globals where we will keep a
2637 // wrong address. It is mostly harmless for locals, but there is
2638 // no point in keeping these anyway when the function wasn't linked.
2639 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2640 !InDebugMap)) &&
2641 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2642 }
2643}
2644
Adrian Prantl3565af42015-09-14 16:46:10 +00002645DIE *DwarfLinker::DIECloner::cloneDIE(
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002646 const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2647 int64_t PCOffset, uint32_t OutOffset, unsigned Flags) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002648 DWARFUnit &U = Unit.getOrigUnit();
2649 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002650 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002651
2652 // Should the DIE appear in the output?
2653 if (!Unit.getInfo(Idx).Keep)
2654 return nullptr;
2655
2656 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002657 // The DIE might have been already created by a forward reference
2658 // (see cloneDieReferenceAttribute()).
2659 DIE *Die = Info.Clone;
2660 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002661 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002662 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002663 Die->setOffset(OutOffset);
Adrian Prantla112ef92015-09-23 17:35:52 +00002664 if ((Unit.hasODR() || Unit.isClangModule()) &&
2665 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
Frederic Riss1c650942015-07-21 22:41:43 +00002666 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2667 !Info.Ctxt->getCanonicalDIEOffset()) {
2668 // We are about to emit a DIE that is the root of its own valid
2669 // DeclContext tree. Make the current offset the canonical offset
2670 // for this context.
2671 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2672 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002673
2674 // Extract and clone every attribute.
2675 DataExtractor Data = U.getDebugInfoExtractor();
Adrian Prantle5162db2015-09-22 22:20:50 +00002676 // Point to the next DIE (generally there is always at least a NULL
2677 // entry after the current one). If this is a lone
2678 // DW_TAG_compile_unit without any children, point to the next unit.
2679 uint32_t NextOffset =
2680 (Idx + 1 < U.getNumDIEs())
2681 ? U.getDIEAtIndex(Idx + 1)->getOffset()
2682 : U.getNextUnitOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002683 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002684
2685 // We could copy the data only if we need to aply a relocation to
2686 // it. After testing, it seems there is no performance downside to
2687 // doing the copy unconditionally, and it makes the code simpler.
2688 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2689 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2690 // Modify the copy with relocated addresses.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002691 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
Frederic Riss31da3242015-03-11 18:45:52 +00002692 // If we applied relocations, we store the value of high_pc that was
2693 // potentially stored in the input DIE. If high_pc is an address
2694 // (Dwarf version == 2), then it might have been relocated to a
2695 // totally unrelated value (because the end address in the object
2696 // file might be start address of another function which got moved
2697 // independantly by the linker). The computation of the actual
2698 // high_pc value is done in cloneAddressAttribute().
2699 AttrInfo.OrigHighPc =
2700 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
Frederic Riss7b5563a2015-08-31 01:43:14 +00002701 // Also store the low_pc. It might get relocated in an
2702 // inline_subprogram that happens at the beginning of its
2703 // inlining function.
2704 AttrInfo.OrigLowPc =
2705 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
Frederic Riss31da3242015-03-11 18:45:52 +00002706 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002707
2708 // Reset the Offset to 0 as we will be working on the local copy of
2709 // the data.
2710 Offset = 0;
2711
Frederic Rissb8b43d52015-03-04 22:07:44 +00002712 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2713 Offset += getULEB128Size(Abbrev->getCode());
2714
Frederic Riss31da3242015-03-11 18:45:52 +00002715 // We are entering a subprogram. Get and propagate the PCOffset.
2716 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2717 PCOffset = Info.AddrAdjust;
2718 AttrInfo.PCOffset = PCOffset;
2719
Frederic Riss29eedc72015-09-11 04:17:30 +00002720 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2721 Flags |= TF_InFunctionScope;
2722 if (!Info.InDebugMap)
2723 Flags |= TF_SkipPC;
2724 }
2725
2726 bool Copied = false;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002727 for (const auto &AttrSpec : Abbrev->attributes()) {
Frederic Riss29eedc72015-09-11 04:17:30 +00002728 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2729 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2730 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2731 // FIXME: dsymutil-classic keeps the old abbreviation around
2732 // even if it's not used. We can remove this (and the copyAbbrev
2733 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2734 if (!Copied) {
2735 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2736 Copied = true;
2737 }
2738 continue;
2739 }
2740
Frederic Rissb8b43d52015-03-04 22:07:44 +00002741 DWARFFormValue Val(AttrSpec.Form);
2742 uint32_t AttrSize = Offset;
2743 Val.extractValue(Data, &Offset, &U);
2744 AttrSize = Offset - AttrSize;
2745
Frederic Riss31da3242015-03-11 18:45:52 +00002746 OutOffset +=
2747 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002748 }
2749
Frederic Rissbce93ff2015-03-16 02:05:10 +00002750 // Look for accelerator entries.
2751 uint16_t Tag = InputDIE.getTag();
2752 // FIXME: This is slightly wrong. An inline_subroutine without a
2753 // low_pc, but with AT_ranges might be interesting to get into the
2754 // accelerator tables too. For now stick with dsymutil's behavior.
2755 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2756 Tag != dwarf::DW_TAG_compile_unit &&
2757 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2758 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2759 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2760 AttrInfo.MangledNameOffset,
2761 Tag == dwarf::DW_TAG_inlined_subroutine);
2762 if (AttrInfo.Name)
2763 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2764 Tag == dwarf::DW_TAG_inlined_subroutine);
2765 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2766 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2767 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2768 }
2769
Adrian Prantle39475d2015-11-10 21:31:05 +00002770 // Determine whether there are any children that we want to keep.
2771 bool HasChildren = false;
2772 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2773 Child = Child->getSibling()) {
2774 unsigned Idx = U.getDIEIndex(Child);
2775 if (Unit.getInfo(Idx).Keep) {
2776 HasChildren = true;
2777 break;
2778 }
2779 }
2780
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002781 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Adrian Prantle39475d2015-11-10 21:31:05 +00002782 if (HasChildren)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002783 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2784 // Assign a permanent abbrev number
Adrian Prantl3565af42015-09-14 16:46:10 +00002785 Linker.AssignAbbrev(NewAbbrev);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002786 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002787
2788 // Add the size of the abbreviation number to the output offset.
2789 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2790
Adrian Prantle39475d2015-11-10 21:31:05 +00002791 if (!HasChildren) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002792 // Update our size.
2793 Die->setSize(OutOffset - Die->getOffset());
2794 return Die;
2795 }
2796
2797 // Recursively clone children.
2798 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2799 Child = Child->getSibling()) {
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002800 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset, Flags)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002801 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002802 OutOffset = Clone->getOffset() + Clone->getSize();
2803 }
2804 }
2805
2806 // Account for the end of children marker.
2807 OutOffset += sizeof(int8_t);
2808 // Update our size.
2809 Die->setSize(OutOffset - Die->getOffset());
2810 return Die;
2811}
2812
Frederic Riss25440872015-03-13 23:30:31 +00002813/// \brief Patch the input object file relevant debug_ranges entries
2814/// and emit them in the output file. Update the relevant attributes
2815/// to point at the new entries.
2816void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2817 DWARFContext &OrigDwarf) const {
2818 DWARFDebugRangeList RangeList;
2819 const auto &FunctionRanges = Unit.getFunctionRanges();
2820 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2821 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2822 OrigDwarf.isLittleEndian(), AddressSize);
2823 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2824 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002825 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002826 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2827 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2828 // Ranges addresses are based on the unit's low_pc. Compute the
Sanjay Patele4b9f502015-12-07 19:21:39 +00002829 // offset we need to apply to adapt to the new unit's low_pc.
Frederic Riss25440872015-03-13 23:30:31 +00002830 int64_t UnitPcOffset = 0;
2831 if (OrigLowPc != -1ULL)
2832 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2833
2834 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002835 uint32_t Offset = RangeAttribute.get();
2836 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002837 RangeList.extract(RangeExtractor, &Offset);
2838 const auto &Entries = RangeList.getEntries();
Frederic Riss94546202015-08-31 05:09:32 +00002839 if (!Entries.empty()) {
2840 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
Frederic Riss25440872015-03-13 23:30:31 +00002841
Frederic Riss25440872015-03-13 23:30:31 +00002842 if (CurrRange == InvalidRange ||
Frederic Riss94546202015-08-31 05:09:32 +00002843 First.StartAddress + OrigLowPc < CurrRange.start() ||
2844 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2845 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2846 if (CurrRange == InvalidRange ||
2847 CurrRange.start() > First.StartAddress + OrigLowPc) {
2848 reportWarning("no mapping for range.");
2849 continue;
2850 }
Frederic Riss25440872015-03-13 23:30:31 +00002851 }
2852 }
2853
2854 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2855 AddressSize);
2856 }
2857}
2858
Frederic Riss563b1b02015-03-14 03:46:51 +00002859/// \brief Generate the debug_aranges entries for \p Unit and if the
2860/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2861/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002862/// FIXME: this could actually be done right in patchRangesForUnit,
2863/// but for the sake of initial bit-for-bit compatibility with legacy
2864/// dsymutil, we have to do it in a delayed pass.
2865void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002866 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002867 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002868 Attr->set(Streamer->getRangesSectionSize());
2869 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002870}
2871
Frederic Riss63786b02015-03-15 20:45:43 +00002872/// \brief Insert the new line info sequence \p Seq into the current
2873/// set of already linked line info \p Rows.
2874static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2875 std::vector<DWARFDebugLine::Row> &Rows) {
2876 if (Seq.empty())
2877 return;
2878
2879 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2880 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2881 Seq.clear();
2882 return;
2883 }
2884
2885 auto InsertPoint = std::lower_bound(
2886 Rows.begin(), Rows.end(), Seq.front(),
2887 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2888 return LHS.Address < RHS.Address;
2889 });
2890
2891 // FIXME: this only removes the unneeded end_sequence if the
2892 // sequences have been inserted in order. using a global sort like
2893 // described in patchLineTableForUnit() and delaying the end_sequene
2894 // elimination to emitLineTableForUnit() we can get rid of all of them.
2895 if (InsertPoint != Rows.end() &&
2896 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2897 *InsertPoint = Seq.front();
2898 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2899 } else {
2900 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2901 }
2902
2903 Seq.clear();
2904}
2905
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002906static void patchStmtList(DIE &Die, DIEInteger Offset) {
2907 for (auto &V : Die.values())
2908 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002909 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002910 return;
2911 }
2912
2913 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2914}
2915
Frederic Riss63786b02015-03-15 20:45:43 +00002916/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2917/// recreate a relocated version of these for the address ranges that
2918/// are present in the binary.
2919void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2920 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002921 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002922 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2923 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2924 if (StmtList == -1ULL)
2925 return;
2926
2927 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002928 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2929 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002930
2931 // Parse the original line info for the unit.
2932 DWARFDebugLine::LineTable LineTable;
2933 uint32_t StmtOffset = StmtList;
2934 StringRef LineData = OrigDwarf.getLineSection().Data;
2935 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2936 Unit.getOrigUnit().getAddressByteSize());
2937 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2938 &StmtOffset);
2939
2940 // This vector is the output line table.
2941 std::vector<DWARFDebugLine::Row> NewRows;
2942 NewRows.reserve(LineTable.Rows.size());
2943
2944 // Current sequence of rows being extracted, before being inserted
2945 // in NewRows.
2946 std::vector<DWARFDebugLine::Row> Seq;
2947 const auto &FunctionRanges = Unit.getFunctionRanges();
2948 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2949
2950 // FIXME: This logic is meant to generate exactly the same output as
2951 // Darwin's classic dsynutil. There is a nicer way to implement this
2952 // by simply putting all the relocated line info in NewRows and simply
2953 // sorting NewRows before passing it to emitLineTableForUnit. This
2954 // should be correct as sequences for a function should stay
2955 // together in the sorted output. There are a few corner cases that
2956 // look suspicious though, and that required to implement the logic
2957 // this way. Revisit that once initial validation is finished.
2958
2959 // Iterate over the object file line info and extract the sequences
2960 // that correspond to linked functions.
2961 for (auto &Row : LineTable.Rows) {
2962 // Check wether we stepped out of the range. The range is
2963 // half-open, but consider accept the end address of the range if
2964 // it is marked as end_sequence in the input (because in that
2965 // case, the relocation offset is accurate and that entry won't
2966 // serve as the start of another function).
2967 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2968 Row.Address > CurrRange.stop() ||
2969 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2970 // We just stepped out of a known range. Insert a end_sequence
2971 // corresponding to the end of the range.
2972 uint64_t StopAddress = CurrRange != InvalidRange
2973 ? CurrRange.stop() + CurrRange.value()
2974 : -1ULL;
2975 CurrRange = FunctionRanges.find(Row.Address);
2976 bool CurrRangeValid =
2977 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2978 if (!CurrRangeValid) {
2979 CurrRange = InvalidRange;
2980 if (StopAddress != -1ULL) {
2981 // Try harder by looking in the DebugMapObject function
2982 // ranges map. There are corner cases where this finds a
2983 // valid entry. It's unclear if this is right or wrong, but
2984 // for now do as dsymutil.
2985 // FIXME: Understand exactly what cases this addresses and
2986 // potentially remove it along with the Ranges map.
2987 auto Range = Ranges.lower_bound(Row.Address);
2988 if (Range != Ranges.begin() && Range != Ranges.end())
2989 --Range;
2990
2991 if (Range != Ranges.end() && Range->first <= Row.Address &&
2992 Range->second.first >= Row.Address) {
2993 StopAddress = Row.Address + Range->second.second;
2994 }
2995 }
2996 }
2997 if (StopAddress != -1ULL && !Seq.empty()) {
2998 // Insert end sequence row with the computed end address, but
2999 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00003000 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00003001 NextLine.Address = StopAddress;
3002 NextLine.EndSequence = 1;
3003 NextLine.PrologueEnd = 0;
3004 NextLine.BasicBlock = 0;
3005 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00003006 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00003007 insertLineSequence(Seq, NewRows);
3008 }
3009
3010 if (!CurrRangeValid)
3011 continue;
3012 }
3013
3014 // Ignore empty sequences.
3015 if (Row.EndSequence && Seq.empty())
3016 continue;
3017
3018 // Relocate row address and add it to the current sequence.
3019 Row.Address += CurrRange.value();
3020 Seq.emplace_back(Row);
3021
3022 if (Row.EndSequence)
3023 insertLineSequence(Seq, NewRows);
3024 }
3025
3026 // Finished extracting, now emit the line tables.
3027 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
3028 // FIXME: LLVM hardcodes it's prologue values. We just copy the
3029 // prologue over and that works because we act as both producer and
3030 // consumer. It would be nicer to have a real configurable line
3031 // table emitter.
3032 if (LineTable.Prologue.Version != 2 ||
3033 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00003034 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00003035 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00003036 else {
3037 MCDwarfLineTableParams Params;
3038 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
3039 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
3040 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
3041 Streamer->emitLineTableForUnit(Params,
3042 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00003043 LineTable.Prologue.MinInstLength, NewRows,
3044 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00003045 }
Frederic Riss63786b02015-03-15 20:45:43 +00003046}
3047
Frederic Rissbce93ff2015-03-16 02:05:10 +00003048void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
3049 Streamer->emitPubNamesForUnit(Unit);
3050 Streamer->emitPubTypesForUnit(Unit);
3051}
3052
Frederic Riss5a642072015-06-05 23:06:11 +00003053/// \brief Read the frame info stored in the object, and emit the
3054/// patched frame descriptions for the linked binary.
3055///
3056/// This is actually pretty easy as the data of the CIEs and FDEs can
3057/// be considered as black boxes and moved as is. The only thing to do
3058/// is to patch the addresses in the headers.
3059void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3060 DWARFContext &OrigDwarf,
3061 unsigned AddrSize) {
3062 StringRef FrameData = OrigDwarf.getDebugFrameSection();
3063 if (FrameData.empty())
3064 return;
3065
3066 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3067 uint32_t InputOffset = 0;
3068
3069 // Store the data of the CIEs defined in this object, keyed by their
3070 // offsets.
3071 DenseMap<uint32_t, StringRef> LocalCIES;
3072
3073 while (Data.isValidOffset(InputOffset)) {
3074 uint32_t EntryOffset = InputOffset;
3075 uint32_t InitialLength = Data.getU32(&InputOffset);
3076 if (InitialLength == 0xFFFFFFFF)
3077 return reportWarning("Dwarf64 bits no supported");
3078
3079 uint32_t CIEId = Data.getU32(&InputOffset);
3080 if (CIEId == 0xFFFFFFFF) {
3081 // This is a CIE, store it.
3082 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3083 LocalCIES[EntryOffset] = CIEData;
3084 // The -4 is to account for the CIEId we just read.
3085 InputOffset += InitialLength - 4;
3086 continue;
3087 }
3088
3089 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3090
3091 // Some compilers seem to emit frame info that doesn't start at
3092 // the function entry point, thus we can't just lookup the address
3093 // in the debug map. Use the linker's range map to see if the FDE
3094 // describes something that we can relocate.
3095 auto Range = Ranges.upper_bound(Loc);
3096 if (Range != Ranges.begin())
3097 --Range;
3098 if (Range == Ranges.end() || Range->first > Loc ||
3099 Range->second.first <= Loc) {
3100 // The +4 is to account for the size of the InitialLength field itself.
3101 InputOffset = EntryOffset + InitialLength + 4;
3102 continue;
3103 }
3104
3105 // This is an FDE, and we have a mapping.
3106 // Have we already emitted a corresponding CIE?
3107 StringRef CIEData = LocalCIES[CIEId];
3108 if (CIEData.empty())
3109 return reportWarning("Inconsistent debug_frame content. Dropping.");
3110
3111 // Look if we already emitted a CIE that corresponds to the
3112 // referenced one (the CIE data is the key of that lookup).
3113 auto IteratorInserted = EmittedCIEs.insert(
3114 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3115 // If there is no CIE yet for this ID, emit it.
3116 if (IteratorInserted.second ||
3117 // FIXME: dsymutil-classic only caches the last used CIE for
3118 // reuse. Mimic that behavior for now. Just removing that
3119 // second half of the condition and the LastCIEOffset variable
3120 // makes the code DTRT.
3121 LastCIEOffset != IteratorInserted.first->getValue()) {
3122 LastCIEOffset = Streamer->getFrameSectionSize();
3123 IteratorInserted.first->getValue() = LastCIEOffset;
3124 Streamer->emitCIE(CIEData);
3125 }
3126
3127 // Emit the FDE with updated address and CIE pointer.
3128 // (4 + AddrSize) is the size of the CIEId + initial_location
3129 // fields that will get reconstructed by emitFDE().
3130 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3131 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3132 Loc + Range->second.second,
3133 FrameData.substr(InputOffset, FDERemainingBytes));
3134 InputOffset += FDERemainingBytes;
3135 }
3136}
3137
Adrian Prantl3565af42015-09-14 16:46:10 +00003138void DwarfLinker::DIECloner::copyAbbrev(
3139 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
Frederic Riss29eedc72015-09-11 04:17:30 +00003140 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3141 dwarf::Form(Abbrev.hasChildren()));
3142
3143 for (const auto &Attr : Abbrev.attributes()) {
3144 uint16_t Form = Attr.Form;
3145 if (hasODR && isODRAttribute(Attr.Attr))
3146 Form = dwarf::DW_FORM_ref_addr;
3147 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3148 }
3149
Adrian Prantl3565af42015-09-14 16:46:10 +00003150 Linker.AssignAbbrev(Copy);
Frederic Riss29eedc72015-09-11 04:17:30 +00003151}
3152
Adrian Prantl20937022015-09-23 17:11:10 +00003153static uint64_t getDwoId(const DWARFDebugInfoEntryMinimal &CUDie,
3154 const DWARFUnit &Unit) {
3155 uint64_t DwoId =
3156 CUDie.getAttributeValueAsUnsignedConstant(&Unit, dwarf::DW_AT_dwo_id, 0);
3157 if (!DwoId)
3158 DwoId = CUDie.getAttributeValueAsUnsignedConstant(&Unit,
3159 dwarf::DW_AT_GNU_dwo_id, 0);
3160 return DwoId;
3161}
3162
Adrian Prantle5162db2015-09-22 22:20:50 +00003163bool DwarfLinker::registerModuleReference(
3164 const DWARFDebugInfoEntryMinimal &CUDie, const DWARFUnit &Unit,
3165 DebugMap &ModuleMap, unsigned Indent) {
3166 std::string PCMfile =
Adrian Prantl20937022015-09-23 17:11:10 +00003167 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_dwo_name, "");
3168 if (PCMfile.empty())
3169 PCMfile =
3170 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_GNU_dwo_name, "");
Adrian Prantle5162db2015-09-22 22:20:50 +00003171 if (PCMfile.empty())
3172 return false;
3173
3174 // Clang module DWARF skeleton CUs abuse this for the path to the module.
3175 std::string PCMpath =
3176 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_comp_dir, "");
Adrian Prantl20937022015-09-23 17:11:10 +00003177 uint64_t DwoId = getDwoId(CUDie, Unit);
Adrian Prantle5162db2015-09-22 22:20:50 +00003178
Adrian Prantla112ef92015-09-23 17:35:52 +00003179 std::string Name =
3180 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_name, "");
3181 if (Name.empty()) {
3182 reportWarning("Anonymous module skeleton CU for " + PCMfile);
3183 return true;
3184 }
3185
Adrian Prantle5162db2015-09-22 22:20:50 +00003186 if (Options.Verbose) {
3187 outs().indent(Indent);
3188 outs() << "Found clang module reference " << PCMfile;
3189 }
3190
Adrian Prantl20937022015-09-23 17:11:10 +00003191 auto Cached = ClangModules.find(PCMfile);
3192 if (Cached != ClangModules.end()) {
3193 if (Cached->second != DwoId)
3194 reportWarning(Twine("hash mismatch: this object file was built against a "
3195 "different version of the module ") + PCMfile);
Adrian Prantle5162db2015-09-22 22:20:50 +00003196 if (Options.Verbose)
3197 outs() << " [cached].\n";
3198 return true;
3199 }
3200 if (Options.Verbose)
3201 outs() << " ...\n";
3202
3203 // Cyclic dependencies are disallowed by Clang, but we still
3204 // shouldn't run into an infinite loop, so mark it as processed now.
Adrian Prantl20937022015-09-23 17:11:10 +00003205 ClangModules.insert({PCMfile, DwoId});
Adrian Prantla112ef92015-09-23 17:35:52 +00003206 loadClangModule(PCMfile, PCMpath, Name, DwoId, ModuleMap, Indent + 2);
Adrian Prantle5162db2015-09-22 22:20:50 +00003207 return true;
3208}
3209
Frederic Risseb85c8f2015-07-24 06:41:11 +00003210ErrorOr<const object::ObjectFile &>
3211DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3212 const DebugMap &Map) {
3213 auto ErrOrObjs =
3214 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
Frederic Rissafeac302015-08-31 05:16:35 +00003215 if (std::error_code EC = ErrOrObjs.getError()) {
Frederic Risseb85c8f2015-07-24 06:41:11 +00003216 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
Frederic Rissafeac302015-08-31 05:16:35 +00003217 return EC;
3218 }
Frederic Risseb85c8f2015-07-24 06:41:11 +00003219 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3220 if (std::error_code EC = ErrOrObj.getError())
3221 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3222 return ErrOrObj;
3223}
3224
Adrian Prantle5162db2015-09-22 22:20:50 +00003225void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
Adrian Prantla112ef92015-09-23 17:35:52 +00003226 StringRef ModuleName, uint64_t DwoId,
3227 DebugMap &ModuleMap, unsigned Indent) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003228 SmallString<80> Path(Options.PrependPath);
3229 if (sys::path::is_relative(Filename))
3230 sys::path::append(Path, ModulePath, Filename);
3231 else
3232 sys::path::append(Path, Filename);
3233 BinaryHolder ObjHolder(Options.Verbose);
3234 auto &Obj =
3235 ModuleMap.addDebugMapObject(Path, sys::TimeValue::PosixZeroTime());
3236 auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
3237 if (!ErrOrObj) {
3238 ClangModules.erase(ClangModules.find(Filename));
3239 return;
3240 }
3241
Benjamin Kramer008f4be2015-09-23 10:38:59 +00003242 std::unique_ptr<CompileUnit> Unit;
Adrian Prantle5162db2015-09-22 22:20:50 +00003243
3244 // Setup access to the debug info.
3245 DWARFContextInMemory DwarfContext(*ErrOrObj);
3246 RelocationManager RelocMgr(*this);
3247 for (const auto &CU : DwarfContext.compile_units()) {
3248 auto *CUDie = CU->getUnitDIE(false);
3249 // Recursively get all modules imported by this one.
3250 if (!registerModuleReference(*CUDie, *CU, ModuleMap, Indent)) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003251 if (Unit) {
3252 errs() << Filename << ": Clang modules are expected to have exactly"
3253 << " 1 compile unit.\n";
3254 exitDsymutil(1);
3255 }
Adrian Prantl20937022015-09-23 17:11:10 +00003256 if (getDwoId(*CUDie, *CU) != DwoId)
3257 reportWarning(
3258 Twine("hash mismatch: this object file was built against a "
3259 "different version of the module ") + Filename);
3260
3261 // Add this module.
Adrian Prantla112ef92015-09-23 17:35:52 +00003262 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
3263 ModuleName);
Adrian Prantle5162db2015-09-22 22:20:50 +00003264 Unit->setHasInterestingContent();
Adrian Prantla112ef92015-09-23 17:35:52 +00003265 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3266 ODRContexts);
Adrian Prantle5162db2015-09-22 22:20:50 +00003267 // Keep everything.
3268 Unit->markEverythingAsKept();
3269 }
3270 }
3271 if (Options.Verbose) {
3272 outs().indent(Indent);
3273 outs() << "cloning .debug_info from " << Filename << "\n";
3274 }
3275
3276 DIECloner(*this, RelocMgr, DIEAlloc, MutableArrayRef<CompileUnit>(*Unit),
3277 Options)
3278 .cloneAllCompileUnits(DwarfContext);
3279}
3280
Adrian Prantl3565af42015-09-14 16:46:10 +00003281void DwarfLinker::DIECloner::cloneAllCompileUnits(
3282 DWARFContextInMemory &DwarfContext) {
3283 if (!Linker.Streamer)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003284 return;
3285
3286 for (auto &CurrentUnit : CompileUnits) {
3287 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Adrian Prantl3565af42015-09-14 16:46:10 +00003288 CurrentUnit.setStartOffset(Linker.OutputDebugInfoSize);
Adrian Prantl3abe18d2015-09-14 23:27:26 +00003289 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PC offset */,
3290 11 /* Unit Header size */, 0);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003291 CurrentUnit.setOutputUnitDIE(OutputDIE);
Adrian Prantl3565af42015-09-14 16:46:10 +00003292 Linker.OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3293 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003294 continue;
3295 // FIXME: for compatibility with the classic dsymutil, we emit
3296 // an empty line table for the unit, even if the unit doesn't
3297 // actually exist in the DIE tree.
Adrian Prantl3565af42015-09-14 16:46:10 +00003298 Linker.patchLineTableForUnit(CurrentUnit, DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003299 if (!OutputDIE)
3300 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003301 Linker.patchRangesForUnit(CurrentUnit, DwarfContext);
3302 Linker.Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3303 Linker.emitAcceleratorEntriesForUnit(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003304 }
3305
Adrian Prantl3565af42015-09-14 16:46:10 +00003306 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003307 return;
3308
3309 // Emit all the compile unit's debug information.
3310 for (auto &CurrentUnit : CompileUnits) {
Adrian Prantl3565af42015-09-14 16:46:10 +00003311 Linker.generateUnitRanges(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003312 CurrentUnit.fixupForwardReferences();
Adrian Prantl3565af42015-09-14 16:46:10 +00003313 Linker.Streamer->emitCompileUnitHeader(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003314 if (!CurrentUnit.getOutputUnitDIE())
3315 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003316 Linker.Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003317 }
3318}
3319
Frederic Rissd3455182015-01-28 18:27:01 +00003320bool DwarfLinker::link(const DebugMap &Map) {
3321
Frederic Rissc99ea202015-02-28 00:29:11 +00003322 if (!createStreamer(Map.getTriple(), OutputFilename))
3323 return false;
3324
Frederic Rissb8b43d52015-03-04 22:07:44 +00003325 // Size of the DIEs (and headers) generated for the linked output.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003326 OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003327 // A unique ID that identifies each compile unit.
Adrian Prantle5162db2015-09-22 22:20:50 +00003328 UnitID = 0;
3329 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3330
Frederic Rissd3455182015-01-28 18:27:01 +00003331 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003332 CurrentDebugObject = Obj.get();
3333
Frederic Rissb9818322015-02-28 00:29:07 +00003334 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003335 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003336 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3337 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003338 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003339
Frederic Riss1036e642015-02-13 23:18:22 +00003340 // Look for relocations that correspond to debug map entries.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003341 RelocationManager RelocMgr(*this);
3342 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003343 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003344 outs() << "No valid relocations found. Skipping.\n";
3345 continue;
3346 }
3347
Frederic Riss563cba62015-01-28 22:15:14 +00003348 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003349 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003350 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003351
Adrian Prantld2793a02015-10-05 23:11:20 +00003352 // In a first phase, just read in the debug info and load all clang modules.
Frederic Rissd3455182015-01-28 18:27:01 +00003353 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003354 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003355 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003356 outs() << "Input compilation unit:";
3357 CUDie->dump(outs(), CU.get(), 0);
3358 }
Adrian Prantld2793a02015-10-05 23:11:20 +00003359
3360 if (!registerModuleReference(*CUDie, *CU, ModuleMap))
Adrian Prantla112ef92015-09-23 17:35:52 +00003361 Units.emplace_back(*CU, UnitID++, !Options.NoODR, "");
Frederic Rissd3455182015-01-28 18:27:01 +00003362 }
Frederic Riss563cba62015-01-28 22:15:14 +00003363
Adrian Prantld2793a02015-10-05 23:11:20 +00003364 // Now build the DIE parent links that we will use during the next phase.
3365 for (auto &CurrentUnit : Units)
3366 analyzeContextInfo(CurrentUnit.getOrigUnit().getUnitDIE(), 0, CurrentUnit,
3367 &ODRContexts.getRoot(), StringPool, ODRContexts);
3368
Frederic Riss84c09a52015-02-13 23:18:34 +00003369 // Then mark all the DIEs that need to be present in the linked
3370 // output and collect some information about them. Note that this
3371 // loop can not be merged with the previous one becaue cross-cu
3372 // references require the ParentIdx to be setup for every CU in
3373 // the object file before calling this.
3374 for (auto &CurrentUnit : Units)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003375 lookForDIEsToKeep(RelocMgr, *CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00003376 CurrentUnit, 0);
3377
Frederic Riss23e20e92015-03-07 01:25:09 +00003378 // The calls to applyValidRelocs inside cloneDIE will walk the
3379 // reloc array again (in the same way findValidRelocsInDebugInfo()
3380 // did). We need to reset the NextValidReloc index to the beginning.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003381 RelocMgr.resetValidRelocs();
3382 if (RelocMgr.hasValidRelocs())
Adrian Prantl3565af42015-09-14 16:46:10 +00003383 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3384 .cloneAllCompileUnits(DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003385 if (!Options.NoOutput && !Units.empty())
Frederic Riss5a642072015-06-05 23:06:11 +00003386 patchFrameInfoForObject(*Obj, DwarfContext,
3387 Units[0].getOrigUnit().getAddressByteSize());
3388
Frederic Riss563cba62015-01-28 22:15:14 +00003389 // Clean-up before starting working on the next object.
3390 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003391 }
3392
Frederic Rissb8b43d52015-03-04 22:07:44 +00003393 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003394 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003395 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003396 Streamer->emitStrings(StringPool);
3397 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003398
Frederic Riss24faade2015-09-02 16:49:13 +00003399 return Options.NoOutput ? true : Streamer->finish(Map);
Frederic Riss231f7142014-12-12 17:31:24 +00003400}
3401}
Frederic Rissd3455182015-01-28 18:27:01 +00003402
Frederic Riss30711fb2015-08-26 05:09:52 +00003403/// \brief Get the offset of string \p S in the string table. This
3404/// can insert a new element or return the offset of a preexisitng
3405/// one.
3406uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3407 if (S.empty() && !Strings.empty())
3408 return 0;
3409
3410 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3411 MapTy::iterator It;
3412 bool Inserted;
3413
3414 // A non-empty string can't be at offset 0, so if we have an entry
3415 // with a 0 offset, it must be a previously interned string.
3416 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3417 if (Inserted || It->getValue().first == 0) {
3418 // Set offset and chain at the end of the entries list.
3419 It->getValue().first = CurrentEndOffset;
3420 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3421 Last->getValue().second = &*It;
3422 Last = &*It;
3423 }
3424 return It->getValue().first;
3425}
3426
3427/// \brief Put \p S into the StringMap so that it gets permanent
3428/// storage, but do not actually link it in the chain of elements
3429/// that go into the output section. A latter call to
3430/// getStringOffset() with the same string will chain it though.
3431StringRef NonRelocatableStringpool::internString(StringRef S) {
3432 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3433 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3434 return InsertResult.first->getKey();
3435}
3436
Frederic Riss65e145c2015-08-26 05:09:55 +00003437void warn(const Twine &Warning, const Twine &Context) {
3438 errs() << Twine("while processing ") + Context + ":\n";
3439 errs() << Twine("warning: ") + Warning + "\n";
3440}
3441
3442bool error(const Twine &Error, const Twine &Context) {
3443 errs() << Twine("while processing ") + Context + ":\n";
3444 errs() << Twine("error: ") + Error + "\n";
3445 return false;
3446}
3447
Frederic Rissb9818322015-02-28 00:29:07 +00003448bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3449 const LinkOptions &Options) {
3450 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003451 return Linker.link(DM);
3452}
3453}
Frederic Riss231f7142014-12-12 17:31:24 +00003454}