blob: edeae4f92f23325f1d8ceff0bebbcb2507a8d68a [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 Riss1af75f72015-03-12 18:45:10 +000013#include "llvm/ADT/IntervalMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000014#include "llvm/ADT/StringMap.h"
15#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000016#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000017#include "llvm/CodeGen/DIE.h"
Zachary Turner82af9432015-01-30 18:07:45 +000018#include "llvm/DebugInfo/DWARF/DWARFContext.h"
19#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000020#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000021#include "llvm/MC/MCAsmBackend.h"
22#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000025#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000026#include "llvm/MC/MCInstrInfo.h"
27#include "llvm/MC/MCObjectFileInfo.h"
28#include "llvm/MC/MCRegisterInfo.h"
29#include "llvm/MC/MCStreamer.h"
Pete Cooper81902a32015-05-15 22:19:42 +000030#include "llvm/MC/MCSubtargetInfo.h"
Frederic Riss1036e642015-02-13 23:18:22 +000031#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000032#include "llvm/Support/Dwarf.h"
33#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000034#include "llvm/Support/TargetRegistry.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000037#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000038#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000039
40namespace llvm {
41namespace dsymutil {
42
Frederic Rissd3455182015-01-28 18:27:01 +000043namespace {
44
Frederic Rissdef4fb72015-02-28 00:29:01 +000045void warn(const Twine &Warning, const Twine &Context) {
46 errs() << Twine("while processing ") + Context + ":\n";
47 errs() << Twine("warning: ") + Warning + "\n";
48}
49
Frederic Rissc99ea202015-02-28 00:29:11 +000050bool error(const Twine &Error, const Twine &Context) {
51 errs() << Twine("while processing ") + Context + ":\n";
52 errs() << Twine("error: ") + Error + "\n";
53 return false;
54}
55
Frederic Riss1af75f72015-03-12 18:45:10 +000056template <typename KeyT, typename ValT>
57using HalfOpenIntervalMap =
58 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
59 IntervalMapHalfOpenInfo<KeyT>>;
60
Frederic Riss25440872015-03-13 23:30:31 +000061typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
62
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000063// FIXME: Delete this structure.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000064struct PatchLocation {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000065 DIE::value_iterator I;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000066
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000067 PatchLocation() = default;
68 PatchLocation(DIE::value_iterator I) : I(I) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000069
70 void set(uint64_t New) const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000071 assert(I);
72 const auto &Old = *I;
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000073 assert(Old.getType() == DIEValue::isInteger);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000074 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000075 }
76
77 uint64_t get() const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000078 assert(I);
79 return I->getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000080 }
81};
82
Frederic Riss563cba62015-01-28 22:15:14 +000083/// \brief Stores all information relating to a compile unit, be it in
84/// its original instance in the object file to its brand new cloned
85/// and linked DIE tree.
86class CompileUnit {
87public:
88 /// \brief Information gathered about a DIE in the object file.
89 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +000090 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss9833de62015-03-06 23:22:53 +000091 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +000092 uint32_t ParentIdx; ///< The index of this DIE's parent.
93 bool Keep; ///< Is the DIE part of the linked output?
94 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +000095 };
96
Frederic Riss3cced052015-03-14 03:46:40 +000097 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
98 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000099 Ranges(RangeAlloc) {
Frederic Riss563cba62015-01-28 22:15:14 +0000100 Info.resize(OrigUnit.getNumDIEs());
101 }
102
Frederic Riss2838f9e2015-03-05 05:29:05 +0000103 CompileUnit(CompileUnit &&RHS)
104 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
105 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000106 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
107 // The CompileUnit container has been 'reserve()'d with the right
108 // size. We cannot move the IntervalMap anyway.
109 llvm_unreachable("CompileUnits should not be moved.");
110 }
David Blaikiea8adc132015-03-04 22:20:52 +0000111
Frederic Rissc3349d42015-02-13 23:18:27 +0000112 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000113
Frederic Riss3cced052015-03-14 03:46:40 +0000114 unsigned getUniqueID() const { return ID; }
115
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +0000116 DIE *getOutputUnitDIE() const { return CUDie; }
117 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000118
Frederic Riss563cba62015-01-28 22:15:14 +0000119 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
120 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
121
Frederic Rissb8b43d52015-03-04 22:07:44 +0000122 uint64_t getStartOffset() const { return StartOffset; }
123 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000124 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000125
Frederic Riss5a62dc32015-03-13 18:35:54 +0000126 uint64_t getLowPc() const { return LowPc; }
127 uint64_t getHighPc() const { return HighPc; }
128
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000129 Optional<PatchLocation> getUnitRangesAttribute() const {
130 return UnitRangeAttribute;
131 }
Frederic Riss25440872015-03-13 23:30:31 +0000132 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000133 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000134 return RangeAttributes;
135 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000136
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000137 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000138 getLocationAttributes() const {
139 return LocationAttributes;
140 }
141
Frederic Riss9d441b62015-03-06 23:22:50 +0000142 /// \brief Compute the end offset for this unit. Must be
143 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000144 /// \returns the next unit offset (which is also the current
145 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000146 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000147
Frederic Riss6afcfce2015-03-13 18:35:57 +0000148 /// \brief Keep track of a forward reference to DIE \p Die in \p
149 /// RefUnit by \p Attr. The attribute should be fixed up later to
150 /// point to the absolute offset of \p Die in the debug_info section.
151 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000152 PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000153
154 /// \brief Apply all fixups recored by noteForwardReference().
155 void fixupForwardReferences();
156
Frederic Riss1af75f72015-03-12 18:45:10 +0000157 /// \brief Add a function range [\p LowPC, \p HighPC) that is
158 /// relocatad by applying offset \p PCOffset.
159 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
160
Frederic Riss5c9c7062015-03-13 23:55:29 +0000161 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000162 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000163 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000164
Frederic Rissdfb97902015-03-14 15:49:07 +0000165 /// \brief Keep track of a location attribute pointing to a location
166 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000167 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000168
Frederic Rissbce93ff2015-03-16 02:05:10 +0000169 /// \brief Add a name accelerator entry for \p Die with \p Name
170 /// which is stored in the string table at \p Offset.
171 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
172 bool SkipPubnamesSection = false);
173
174 /// \brief Add a type accelerator entry for \p Die with \p Name
175 /// which is stored in the string table at \p Offset.
176 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
177
178 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000179 StringRef Name; ///< Name of the entry.
180 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000181 uint32_t NameOffset; ///< Offset of Name in the string pool.
182 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
183
184 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
185 bool SkipPubSection = false)
186 : Name(Name), Die(Die), NameOffset(NameOffset),
187 SkipPubSection(SkipPubSection) {}
188 };
189
190 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
191 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
192
Frederic Riss563cba62015-01-28 22:15:14 +0000193private:
194 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000195 unsigned ID;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000196 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +0000197 DIE *CUDie; ///< Root of the linked DIE tree.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000198
199 uint64_t StartOffset;
200 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000201
Frederic Riss5a62dc32015-03-13 18:35:54 +0000202 uint64_t LowPc;
203 uint64_t HighPc;
204
Frederic Riss9833de62015-03-06 23:22:53 +0000205 /// \brief A list of attributes to fixup with the absolute offset of
206 /// a DIE in the debug_info section.
207 ///
208 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000209 /// cloning because for cross-cu forward refences the target DIE's
210 /// offset isn't known you emit the reference attribute.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000211 std::vector<std::tuple<DIE *, const CompileUnit *, PatchLocation>>
Frederic Riss6afcfce2015-03-13 18:35:57 +0000212 ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000213
Frederic Riss25440872015-03-13 23:30:31 +0000214 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000215 /// \brief The ranges in that interval map are the PC ranges for
216 /// functions in this unit, associated with the PC offset to apply
217 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000218 FunctionIntervals Ranges;
219
220 /// \brief DW_AT_ranges attributes to patch after we have gathered
221 /// all the unit's function addresses.
222 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000223 std::vector<PatchLocation> RangeAttributes;
224 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000225 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000226
227 /// \brief Location attributes that need to be transfered from th
228 /// original debug_loc section to the liked one. They are stored
229 /// along with the PC offset that is to be applied to their
230 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000231 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000232
233 /// \brief Accelerator entries for the unit, both for the pub*
234 /// sections and the apple* ones.
235 /// @{
236 std::vector<AccelInfo> Pubnames;
237 std::vector<AccelInfo> Pubtypes;
238 /// @}
Frederic Riss563cba62015-01-28 22:15:14 +0000239};
240
Frederic Riss9d441b62015-03-06 23:22:50 +0000241uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000242 NextUnitOffset = StartOffset + 11 /* Header size */;
243 // The root DIE might be null, meaning that the Unit had nothing to
244 // contribute to the linked output. In that case, we will emit the
245 // unit header without any actual DIE.
246 if (CUDie)
247 NextUnitOffset += CUDie->getSize();
248 return NextUnitOffset;
249}
250
Frederic Riss6afcfce2015-03-13 18:35:57 +0000251/// \brief Keep track of a forward cross-cu reference from this unit
252/// to \p Die that lives in \p RefUnit.
253void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000254 PatchLocation Attr) {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000255 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000256}
257
258/// \brief Apply all fixups recorded by noteForwardReference().
259void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000260 for (const auto &Ref : ForwardDIEReferences) {
261 DIE *RefDie;
262 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000263 PatchLocation Attr;
Frederic Riss6afcfce2015-03-13 18:35:57 +0000264 std::tie(RefDie, RefUnit, Attr) = Ref;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000265 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000266 }
Frederic Riss9833de62015-03-06 23:22:53 +0000267}
268
Frederic Riss5a62dc32015-03-13 18:35:54 +0000269void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
270 int64_t PcOffset) {
271 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
272 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
273 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000274}
275
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000276void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000277 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
278 RangeAttributes.push_back(Attr);
279 else
280 UnitRangeAttribute = Attr;
281}
282
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000283void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000284 LocationAttributes.emplace_back(Attr, PcOffset);
285}
286
Frederic Rissbce93ff2015-03-16 02:05:10 +0000287/// \brief Add a name accelerator entry for \p Die with \p Name
288/// which is stored in the string table at \p Offset.
289void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
290 uint32_t Offset, bool SkipPubSection) {
291 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
292}
293
294/// \brief Add a type accelerator entry for \p Die with \p Name
295/// which is stored in the string table at \p Offset.
296void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
297 uint32_t Offset) {
298 Pubtypes.emplace_back(Name, Die, Offset, false);
299}
300
Frederic Rissef648462015-03-06 17:56:30 +0000301/// \brief A string table that doesn't need relocations.
302///
303/// We are doing a final link, no need for a string table that
304/// has relocation entries for every reference to it. This class
305/// provides this ablitity by just associating offsets with
306/// strings.
307class NonRelocatableStringpool {
308public:
309 /// \brief Entries are stored into the StringMap and simply linked
310 /// together through the second element of this pair in order to
311 /// keep track of insertion order.
312 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
313 MapTy;
314
315 NonRelocatableStringpool()
316 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
317 // Legacy dsymutil puts an empty string at the start of the line
318 // table.
319 getStringOffset("");
320 }
321
322 /// \brief Get the offset of string \p S in the string table. This
323 /// can insert a new element or return the offset of a preexisitng
324 /// one.
325 uint32_t getStringOffset(StringRef S);
326
327 /// \brief Get permanent storage for \p S (but do not necessarily
328 /// emit \p S in the output section).
329 /// \returns The StringRef that points to permanent storage to use
330 /// in place of \p S.
331 StringRef internString(StringRef S);
332
333 // \brief Return the first entry of the string table.
334 const MapTy::MapEntryTy *getFirstEntry() const {
335 return getNextEntry(&Sentinel);
336 }
337
338 // \brief Get the entry following \p E in the string table or null
339 // if \p E was the last entry.
340 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
341 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
342 }
343
344 uint64_t getSize() { return CurrentEndOffset; }
345
346private:
347 MapTy Strings;
348 uint32_t CurrentEndOffset;
349 MapTy::MapEntryTy Sentinel, *Last;
350};
351
352/// \brief Get the offset of string \p S in the string table. This
353/// can insert a new element or return the offset of a preexisitng
354/// one.
355uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
356 if (S.empty() && !Strings.empty())
357 return 0;
358
359 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
360 MapTy::iterator It;
361 bool Inserted;
362
363 // A non-empty string can't be at offset 0, so if we have an entry
364 // with a 0 offset, it must be a previously interned string.
365 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
366 if (Inserted || It->getValue().first == 0) {
367 // Set offset and chain at the end of the entries list.
368 It->getValue().first = CurrentEndOffset;
369 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
370 Last->getValue().second = &*It;
371 Last = &*It;
372 }
373 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000374}
Frederic Rissef648462015-03-06 17:56:30 +0000375
376/// \brief Put \p S into the StringMap so that it gets permanent
377/// storage, but do not actually link it in the chain of elements
378/// that go into the output section. A latter call to
379/// getStringOffset() with the same string will chain it though.
380StringRef NonRelocatableStringpool::internString(StringRef S) {
381 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
382 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
383 return InsertResult.first->getKey();
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000384}
Frederic Rissef648462015-03-06 17:56:30 +0000385
Frederic Rissc99ea202015-02-28 00:29:11 +0000386/// \brief The Dwarf streaming logic
387///
388/// All interactions with the MC layer that is used to build the debug
389/// information binary representation are handled in this class.
390class DwarfStreamer {
391 /// \defgroup MCObjects MC layer objects constructed by the streamer
392 /// @{
393 std::unique_ptr<MCRegisterInfo> MRI;
394 std::unique_ptr<MCAsmInfo> MAI;
395 std::unique_ptr<MCObjectFileInfo> MOFI;
396 std::unique_ptr<MCContext> MC;
397 MCAsmBackend *MAB; // Owned by MCStreamer
398 std::unique_ptr<MCInstrInfo> MII;
399 std::unique_ptr<MCSubtargetInfo> MSTI;
400 MCCodeEmitter *MCE; // Owned by MCStreamer
401 MCStreamer *MS; // Owned by AsmPrinter
402 std::unique_ptr<TargetMachine> TM;
403 std::unique_ptr<AsmPrinter> Asm;
404 /// @}
405
406 /// \brief the file we stream the linked Dwarf to.
407 std::unique_ptr<raw_fd_ostream> OutFile;
408
Frederic Riss25440872015-03-13 23:30:31 +0000409 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000410 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000411 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000412 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000413
Frederic Rissbce93ff2015-03-16 02:05:10 +0000414 /// \brief Emit the pubnames or pubtypes section contribution for \p
415 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000416 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000417 const CompileUnit &Unit,
418 const std::vector<CompileUnit::AccelInfo> &Names);
419
Frederic Rissc99ea202015-02-28 00:29:11 +0000420public:
421 /// \brief Actually create the streamer and the ouptut file.
422 ///
423 /// This could be done directly in the constructor, but it feels
424 /// more natural to handle errors through return value.
425 bool init(Triple TheTriple, StringRef OutputFilename);
426
Frederic Rissb8b43d52015-03-04 22:07:44 +0000427 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000428 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000429
430 AsmPrinter &getAsmPrinter() const { return *Asm; }
431
432 /// \brief Set the current output section to debug_info and change
433 /// the MC Dwarf version to \p DwarfVersion.
434 void switchToDebugInfoSection(unsigned DwarfVersion);
435
436 /// \brief Emit the compilation unit header for \p Unit in the
437 /// debug_info section.
438 ///
439 /// As a side effect, this also switches the current Dwarf version
440 /// of the MC layer to the one of U.getOrigUnit().
441 void emitCompileUnitHeader(CompileUnit &Unit);
442
443 /// \brief Recursively emit the DIE tree rooted at \p Die.
444 void emitDIE(DIE &Die);
445
446 /// \brief Emit the abbreviation table \p Abbrevs to the
447 /// debug_abbrev section.
448 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000449
450 /// \brief Emit the string table described by \p Pool.
451 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000452
453 /// \brief Emit debug_ranges for \p FuncRange by translating the
454 /// original \p Entries.
455 void emitRangesEntries(
456 int64_t UnitPcOffset, uint64_t OrigLowPc,
457 FunctionIntervals::const_iterator FuncRange,
458 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
459 unsigned AddressSize);
460
Frederic Riss563b1b02015-03-14 03:46:51 +0000461 /// \brief Emit debug_aranges entries for \p Unit and if \p
462 /// DoRangesSection is true, also emit the debug_ranges entries for
463 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
464 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000465
466 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000467
468 /// \brief Emit the debug_loc contribution for \p Unit by copying
469 /// the entries from \p Dwarf and offseting them. Update the
470 /// location attributes to point to the new entries.
471 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000472
473 /// \brief Emit the line table described in \p Rows into the
474 /// debug_line section.
475 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
476 std::vector<DWARFDebugLine::Row> &Rows,
477 unsigned AdddressSize);
478
479 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000480
481 /// \brief Emit the .debug_pubnames contribution for \p Unit.
482 void emitPubNamesForUnit(const CompileUnit &Unit);
483
484 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
485 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000486
487 /// \brief Emit a CIE.
488 void emitCIE(StringRef CIEBytes);
489
490 /// \brief Emit an FDE with data \p Bytes.
491 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
492 StringRef Bytes);
493
494 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000495};
496
497bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
498 std::string ErrorStr;
499 std::string TripleName;
500 StringRef Context = "dwarf streamer init";
501
502 // Get the target.
503 const Target *TheTarget =
504 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
505 if (!TheTarget)
506 return error(ErrorStr, Context);
507 TripleName = TheTriple.getTriple();
508
509 // Create all the MC Objects.
510 MRI.reset(TheTarget->createMCRegInfo(TripleName));
511 if (!MRI)
512 return error(Twine("no register info for target ") + TripleName, Context);
513
514 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
515 if (!MAI)
516 return error("no asm info for target " + TripleName, Context);
517
518 MOFI.reset(new MCObjectFileInfo);
519 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000520 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
Frederic Rissc99ea202015-02-28 00:29:11 +0000521 *MC);
522
523 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
524 if (!MAB)
525 return error("no asm backend for target " + TripleName, Context);
526
527 MII.reset(TheTarget->createMCInstrInfo());
528 if (!MII)
529 return error("no instr info info for target " + TripleName, Context);
530
531 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
532 if (!MSTI)
533 return error("no subtarget info for target " + TripleName, Context);
534
Eric Christopher0169e422015-03-10 22:03:14 +0000535 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000536 if (!MCE)
537 return error("no code emitter for target " + TripleName, Context);
538
539 // Create the output file.
540 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000541 OutFile =
542 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000543 if (EC)
544 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
545
Rafael Espindolaf696df12015-03-16 22:29:29 +0000546 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000547 *MSTI, false,
548 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000549 if (!MS)
550 return error("no object streamer for target " + TripleName, Context);
551
552 // Finally create the AsmPrinter we'll use to emit the DIEs.
553 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
554 if (!TM)
555 return error("no target machine for target " + TripleName, Context);
556
557 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
558 if (!Asm)
559 return error("no asm printer for target " + TripleName, Context);
560
Frederic Riss25440872015-03-13 23:30:31 +0000561 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000562 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000563 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000564 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000565
Frederic Rissc99ea202015-02-28 00:29:11 +0000566 return true;
567}
568
569bool DwarfStreamer::finish() {
570 MS->Finish();
571 return true;
572}
573
Frederic Rissb8b43d52015-03-04 22:07:44 +0000574/// \brief Set the current output section to debug_info and change
575/// the MC Dwarf version to \p DwarfVersion.
576void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
577 MS->SwitchSection(MOFI->getDwarfInfoSection());
578 MC->setDwarfVersion(DwarfVersion);
579}
580
581/// \brief Emit the compilation unit header for \p Unit in the
582/// debug_info section.
583///
584/// A Dwarf scetion header is encoded as:
585/// uint32_t Unit length (omiting this field)
586/// uint16_t Version
587/// uint32_t Abbreviation table offset
588/// uint8_t Address size
589///
590/// Leading to a total of 11 bytes.
591void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
592 unsigned Version = Unit.getOrigUnit().getVersion();
593 switchToDebugInfoSection(Version);
594
595 // Emit size of content not including length itself. The size has
596 // already been computed in CompileUnit::computeOffsets(). Substract
597 // 4 to that size to account for the length field.
598 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
599 Asm->EmitInt16(Version);
600 // We share one abbreviations table across all units so it's always at the
601 // start of the section.
602 Asm->EmitInt32(0);
603 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
604}
605
606/// \brief Emit the \p Abbrevs array as the shared abbreviation table
607/// for the linked Dwarf file.
608void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
609 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
610 Asm->emitDwarfAbbrevs(Abbrevs);
611}
612
613/// \brief Recursively emit the DIE tree rooted at \p Die.
614void DwarfStreamer::emitDIE(DIE &Die) {
615 MS->SwitchSection(MOFI->getDwarfInfoSection());
616 Asm->emitDwarfDIE(Die);
617}
618
Frederic Rissef648462015-03-06 17:56:30 +0000619/// \brief Emit the debug_str section stored in \p Pool.
620void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000621 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000622 for (auto *Entry = Pool.getFirstEntry(); Entry;
623 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000624 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000625 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
626}
627
Frederic Riss25440872015-03-13 23:30:31 +0000628/// \brief Emit the debug_range section contents for \p FuncRange by
629/// translating the original \p Entries. The debug_range section
630/// format is totally trivial, consisting just of pairs of address
631/// sized addresses describing the ranges.
632void DwarfStreamer::emitRangesEntries(
633 int64_t UnitPcOffset, uint64_t OrigLowPc,
634 FunctionIntervals::const_iterator FuncRange,
635 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
636 unsigned AddressSize) {
637 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
638
639 // Offset each range by the right amount.
640 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
641 for (const auto &Range : Entries) {
642 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
643 warn("unsupported base address selection operation",
644 "emitting debug_ranges");
645 break;
646 }
647 // Do not emit empty ranges.
648 if (Range.StartAddress == Range.EndAddress)
649 continue;
650
651 // All range entries should lie in the function range.
652 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
653 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
654 warn("inconsistent range data.", "emitting debug_ranges");
655 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
656 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
657 RangesSectionSize += 2 * AddressSize;
658 }
659
660 // Add the terminator entry.
661 MS->EmitIntValue(0, AddressSize);
662 MS->EmitIntValue(0, AddressSize);
663 RangesSectionSize += 2 * AddressSize;
664}
665
Frederic Riss563b1b02015-03-14 03:46:51 +0000666/// \brief Emit the debug_aranges contribution of a unit and
667/// if \p DoDebugRanges is true the debug_range contents for a
668/// compile_unit level DW_AT_ranges attribute (Which are basically the
669/// same thing with a different base address).
670/// Just aggregate all the ranges gathered inside that unit.
671void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
672 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000673 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
674 // Gather the ranges in a vector, so that we can simplify them. The
675 // IntervalMap will have coalesced the non-linked ranges, but here
676 // we want to coalesce the linked addresses.
677 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
678 const auto &FunctionRanges = Unit.getFunctionRanges();
679 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
680 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000681 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
682 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000683
684 // The object addresses where sorted, but again, the linked
685 // addresses might end up in a different order.
686 std::sort(Ranges.begin(), Ranges.end());
687
Frederic Riss563b1b02015-03-14 03:46:51 +0000688 if (!Ranges.empty()) {
689 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
690
Rafael Espindola9ab09232015-03-17 20:07:06 +0000691 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
692 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000693
694 unsigned HeaderSize =
695 sizeof(int32_t) + // Size of contents (w/o this field
696 sizeof(int16_t) + // DWARF ARange version number
697 sizeof(int32_t) + // Offset of CU in the .debug_info section
698 sizeof(int8_t) + // Pointer Size (in bytes)
699 sizeof(int8_t); // Segment Size (in bytes)
700
701 unsigned TupleSize = AddressSize * 2;
702 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
703
704 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000705 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000706 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
707 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
708 Asm->EmitInt8(AddressSize); // Address size
709 Asm->EmitInt8(0); // Segment size
710
Lang Hames9ff69c82015-04-24 19:11:51 +0000711 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000712
713 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
714 ++Range) {
715 uint64_t RangeStart = Range->first;
716 MS->EmitIntValue(RangeStart, AddressSize);
717 while ((Range + 1) != End && Range->second == (Range + 1)->first)
718 ++Range;
719 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
720 }
721
722 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000723 Asm->OutStreamer->EmitIntValue(0, AddressSize);
724 Asm->OutStreamer->EmitIntValue(0, AddressSize);
725 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000726 }
727
728 if (!DoDebugRanges)
729 return;
730
731 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
732 // Offset each range by the right amount.
733 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000734 // Emit coalesced ranges.
735 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000736 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000737 while (Range + 1 != End && Range->second == (Range + 1)->first)
738 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000739 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000740 RangesSectionSize += 2 * AddressSize;
741 }
742
743 // Add the terminator entry.
744 MS->EmitIntValue(0, AddressSize);
745 MS->EmitIntValue(0, AddressSize);
746 RangesSectionSize += 2 * AddressSize;
747}
748
Frederic Rissdfb97902015-03-14 15:49:07 +0000749/// \brief Emit location lists for \p Unit and update attribtues to
750/// point to the new entries.
751void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
752 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000753 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000754
755 if (Attributes.empty())
756 return;
757
758 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
759
760 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
761 const DWARFSection &InputSec = Dwarf.getLocSection();
762 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
763 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000764 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000765 int64_t UnitPcOffset = 0;
766 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
767 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
768 if (OrigLowPc != -1ULL)
769 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
770
771 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000772 uint32_t Offset = Attr.first.get();
773 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000774 // This is the quantity to add to the old location address to get
775 // the correct address for the new one.
776 int64_t LocPcOffset = Attr.second + UnitPcOffset;
777 while (Data.isValidOffset(Offset)) {
778 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
779 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
780 LocSectionSize += 2 * AddressSize;
781 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000782 Asm->OutStreamer->EmitIntValue(0, AddressSize);
783 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000784 break;
785 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000786 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
787 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000788 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000789 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000790 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000791 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000792 StringRef(InputSec.Data.substr(Offset, Length)));
793 Offset += Length;
794 LocSectionSize += Length + 2;
795 }
796 }
797}
798
Frederic Riss63786b02015-03-15 20:45:43 +0000799void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
800 unsigned MinInstLength,
801 std::vector<DWARFDebugLine::Row> &Rows,
802 unsigned PointerSize) {
803 // Switch to the section where the table will be emitted into.
804 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000805 MCSymbol *LineStartSym = MC->createTempSymbol();
806 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000807
808 // The first 4 bytes is the total length of the information for this
809 // compilation unit (not including these 4 bytes for the length).
810 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000811 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000812 // Copy Prologue.
813 MS->EmitBytes(PrologueBytes);
814 LineSectionSize += PrologueBytes.size() + 4;
815
Frederic Rissc3820d02015-03-15 22:20:28 +0000816 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000817 raw_svector_ostream EncodingOS(EncodingBuffer);
818
819 if (Rows.empty()) {
820 // We only have the dummy entry, dsymutil emits an entry with a 0
821 // address in that case.
822 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
823 MS->EmitBytes(EncodingOS.str());
824 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000825 MS->EmitLabel(LineEndSym);
826 return;
827 }
828
829 // Line table state machine fields
830 unsigned FileNum = 1;
831 unsigned LastLine = 1;
832 unsigned Column = 0;
833 unsigned IsStatement = 1;
834 unsigned Isa = 0;
835 uint64_t Address = -1ULL;
836
837 unsigned RowsSinceLastSequence = 0;
838
839 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
840 auto &Row = Rows[Idx];
841
842 int64_t AddressDelta;
843 if (Address == -1ULL) {
844 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
845 MS->EmitULEB128IntValue(PointerSize + 1);
846 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
847 MS->EmitIntValue(Row.Address, PointerSize);
848 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
849 AddressDelta = 0;
850 } else {
851 AddressDelta = (Row.Address - Address) / MinInstLength;
852 }
853
854 // FIXME: code copied and transfromed from
855 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
856 // this code, but the current compatibility requirement with
857 // classic dsymutil makes it hard. Revisit that once this
858 // requirement is dropped.
859
860 if (FileNum != Row.File) {
861 FileNum = Row.File;
862 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
863 MS->EmitULEB128IntValue(FileNum);
864 LineSectionSize += 1 + getULEB128Size(FileNum);
865 }
866 if (Column != Row.Column) {
867 Column = Row.Column;
868 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
869 MS->EmitULEB128IntValue(Column);
870 LineSectionSize += 1 + getULEB128Size(Column);
871 }
872
873 // FIXME: We should handle the discriminator here, but dsymutil
874 // doesn' consider it, thus ignore it for now.
875
876 if (Isa != Row.Isa) {
877 Isa = Row.Isa;
878 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
879 MS->EmitULEB128IntValue(Isa);
880 LineSectionSize += 1 + getULEB128Size(Isa);
881 }
882 if (IsStatement != Row.IsStmt) {
883 IsStatement = Row.IsStmt;
884 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
885 LineSectionSize += 1;
886 }
887 if (Row.BasicBlock) {
888 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
889 LineSectionSize += 1;
890 }
891
892 if (Row.PrologueEnd) {
893 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
894 LineSectionSize += 1;
895 }
896
897 if (Row.EpilogueBegin) {
898 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
899 LineSectionSize += 1;
900 }
901
902 int64_t LineDelta = int64_t(Row.Line) - LastLine;
903 if (!Row.EndSequence) {
904 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
905 MS->EmitBytes(EncodingOS.str());
906 LineSectionSize += EncodingBuffer.size();
907 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000908 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000909 Address = Row.Address;
910 LastLine = Row.Line;
911 RowsSinceLastSequence++;
912 } else {
913 if (LineDelta) {
914 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
915 MS->EmitSLEB128IntValue(LineDelta);
916 LineSectionSize += 1 + getSLEB128Size(LineDelta);
917 }
918 if (AddressDelta) {
919 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
920 MS->EmitULEB128IntValue(AddressDelta);
921 LineSectionSize += 1 + getULEB128Size(AddressDelta);
922 }
923 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
924 MS->EmitBytes(EncodingOS.str());
925 LineSectionSize += EncodingBuffer.size();
926 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000927 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000928 Address = -1ULL;
929 LastLine = FileNum = IsStatement = 1;
930 RowsSinceLastSequence = Column = Isa = 0;
931 }
932 }
933
934 if (RowsSinceLastSequence) {
935 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
936 MS->EmitBytes(EncodingOS.str());
937 LineSectionSize += EncodingBuffer.size();
938 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000939 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000940 }
941
942 MS->EmitLabel(LineEndSym);
943}
944
Frederic Rissbce93ff2015-03-16 02:05:10 +0000945/// \brief Emit the pubnames or pubtypes section contribution for \p
946/// Unit into \p Sec. The data is provided in \p Names.
947void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000948 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000949 const std::vector<CompileUnit::AccelInfo> &Names) {
950 if (Names.empty())
951 return;
952
953 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +0000954 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +0000955 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
956 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +0000957
958 bool HeaderEmitted = false;
959 // Emit the pubnames for this compilation unit.
960 for (const auto &Name : Names) {
961 if (Name.SkipPubSection)
962 continue;
963
964 if (!HeaderEmitted) {
965 // Emit the header.
966 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +0000967 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000968 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +0000969 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +0000970 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
971 HeaderEmitted = true;
972 }
973 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +0000974 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +0000975 StringRef(Name.Name.data(), Name.Name.size() + 1));
976 }
977
978 if (!HeaderEmitted)
979 return;
980 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +0000981 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000982}
983
984/// \brief Emit .debug_pubnames for \p Unit.
985void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
986 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
987 "names", Unit, Unit.getPubnames());
988}
989
990/// \brief Emit .debug_pubtypes for \p Unit.
991void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
992 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
993 "types", Unit, Unit.getPubtypes());
994}
995
Frederic Riss5a642072015-06-05 23:06:11 +0000996/// \brief Emit a CIE into the debug_frame section.
997void DwarfStreamer::emitCIE(StringRef CIEBytes) {
998 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
999
1000 MS->EmitBytes(CIEBytes);
1001 FrameSectionSize += CIEBytes.size();
1002}
1003
1004/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1005/// contains the FDE data without the length, CIE offset and address
1006/// which will be replaced with the paramter values.
1007void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1008 uint32_t Address, StringRef FDEBytes) {
1009 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1010
1011 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1012 MS->EmitIntValue(CIEOffset, 4);
1013 MS->EmitIntValue(Address, AddrSize);
1014 MS->EmitBytes(FDEBytes);
1015 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1016}
1017
Frederic Rissd3455182015-01-28 18:27:01 +00001018/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001019///
1020/// The link of the dwarf information from the object files will be
1021/// driven by the selection of 'root DIEs', which are DIEs that
1022/// describe variables or functions that are present in the linked
1023/// binary (and thus have entries in the debug map). All the debug
1024/// information that will be linked (the DIEs, but also the line
1025/// tables, ranges, ...) is derived from that set of root DIEs.
1026///
1027/// The root DIEs are identified because they contain relocations that
1028/// correspond to a debug map entry at specific places (the low_pc for
1029/// a function, the location for a variable). These relocations are
1030/// called ValidRelocs in the DwarfLinker and are gathered as a very
1031/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001032class DwarfLinker {
1033public:
Frederic Rissb9818322015-02-28 00:29:07 +00001034 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1035 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001036 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001037
Frederic Rissb8b43d52015-03-04 22:07:44 +00001038 ~DwarfLinker() {
1039 for (auto *Abbrev : Abbreviations)
1040 delete Abbrev;
1041 }
1042
Frederic Rissd3455182015-01-28 18:27:01 +00001043 /// \brief Link the contents of the DebugMap.
1044 bool link(const DebugMap &);
1045
1046private:
Frederic Riss563cba62015-01-28 22:15:14 +00001047 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001048 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001049
1050 /// \brief Called at the end of a debug object link.
1051 void endDebugObject();
1052
Frederic Riss1036e642015-02-13 23:18:22 +00001053 /// \defgroup FindValidRelocations Translate debug map into a list
1054 /// of relevant relocations
1055 ///
1056 /// @{
1057 struct ValidReloc {
1058 uint32_t Offset;
1059 uint32_t Size;
1060 uint64_t Addend;
1061 const DebugMapObject::DebugMapEntry *Mapping;
1062
1063 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1064 const DebugMapObject::DebugMapEntry *Mapping)
1065 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1066
1067 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1068 };
1069
1070 /// \brief The valid relocations for the current DebugMapObject.
1071 /// This vector is sorted by relocation offset.
1072 std::vector<ValidReloc> ValidRelocs;
1073
1074 /// \brief Index into ValidRelocs of the next relocation to
1075 /// consider. As we walk the DIEs in acsending file offset and as
1076 /// ValidRelocs is sorted by file offset, keeping this index
1077 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001078 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001079 unsigned NextValidReloc;
1080
1081 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1082 const DebugMapObject &DMO);
1083
1084 bool findValidRelocs(const object::SectionRef &Section,
1085 const object::ObjectFile &Obj,
1086 const DebugMapObject &DMO);
1087
1088 void findValidRelocsMachO(const object::SectionRef &Section,
1089 const object::MachOObjectFile &Obj,
1090 const DebugMapObject &DMO);
1091 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001092
Frederic Riss84c09a52015-02-13 23:18:34 +00001093 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1094 ///
1095 /// @{
1096 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1097 /// keep. Store that information in \p CU's DIEInfo.
1098 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1099 const DebugMapObject &DMO, CompileUnit &CU,
1100 unsigned Flags);
1101
1102 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1103 enum TravesalFlags {
1104 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1105 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1106 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1107 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1108 };
1109
1110 /// \brief Mark the passed DIE as well as all the ones it depends on
1111 /// as kept.
1112 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1113 CompileUnit::DIEInfo &MyInfo,
1114 const DebugMapObject &DMO, CompileUnit &CU,
1115 unsigned Flags);
1116
1117 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1118 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1119 unsigned Flags);
1120
1121 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1122 CompileUnit &Unit,
1123 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1124
1125 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1126 CompileUnit &Unit,
1127 CompileUnit::DIEInfo &MyInfo,
1128 unsigned Flags);
1129
1130 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1131 CompileUnit::DIEInfo &Info);
1132 /// @}
1133
Frederic Rissb8b43d52015-03-04 22:07:44 +00001134 /// \defgroup Linking Methods used to link the debug information
1135 ///
1136 /// @{
1137 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1138 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1139 /// stripped out and addresses have been rewritten according to the
1140 /// debug map.
1141 ///
1142 /// \param OutOffset is the offset the cloned DIE in the output
1143 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001144 /// \param PCOffset (while cloning a function scope) is the offset
1145 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001146 ///
1147 /// \returns the root of the cloned tree.
1148 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001149 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001150
1151 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1152
Frederic Riss31da3242015-03-11 18:45:52 +00001153 /// \brief Information gathered and exchanged between the various
1154 /// clone*Attributes helpers about the attributes of a particular DIE.
1155 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001156 const char *Name, *MangledName; ///< Names.
1157 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1158
Frederic Riss31da3242015-03-11 18:45:52 +00001159 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1160 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1161
Frederic Rissbce93ff2015-03-16 02:05:10 +00001162 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1163 bool IsDeclaration; ///< Is this DIE only a declaration?
1164
1165 AttributesInfo()
1166 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1167 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1168 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001169 };
1170
Frederic Rissb8b43d52015-03-04 22:07:44 +00001171 /// \brief Helper for cloneDIE.
1172 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1173 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001174 const AttributeSpec AttrSpec, unsigned AttrSize,
1175 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001176
1177 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001178 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1179 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001180
1181 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001182 unsigned
1183 cloneDieReferenceAttribute(DIE &Die,
1184 const DWARFDebugInfoEntryMinimal &InputDIE,
1185 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001186 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001187
1188 /// \brief Helper for cloneDIE.
1189 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1190 const DWARFFormValue &Val, unsigned AttrSize);
1191
1192 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001193 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1194 const DWARFFormValue &Val,
1195 const CompileUnit &Unit, AttributesInfo &Info);
1196
1197 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001198 unsigned cloneScalarAttribute(DIE &Die,
1199 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001200 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001201 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001202 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001203
Frederic Riss23e20e92015-03-07 01:25:09 +00001204 /// \brief Helper for cloneDIE.
1205 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1206 bool isLittleEndian);
1207
Frederic Rissb8b43d52015-03-04 22:07:44 +00001208 /// \brief Assign an abbreviation number to \p Abbrev
1209 void AssignAbbrev(DIEAbbrev &Abbrev);
1210
1211 /// \brief FoldingSet that uniques the abbreviations.
1212 FoldingSet<DIEAbbrev> AbbreviationsSet;
1213 /// \brief Storage for the unique Abbreviations.
1214 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1215 /// be changed to a vecot of unique_ptrs.
1216 std::vector<DIEAbbrev *> Abbreviations;
1217
Frederic Riss25440872015-03-13 23:30:31 +00001218 /// \brief Compute and emit debug_ranges section for \p Unit, and
1219 /// patch the attributes referencing it.
1220 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1221
1222 /// \brief Generate and emit the DW_AT_ranges attribute for a
1223 /// compile_unit if it had one.
1224 void generateUnitRanges(CompileUnit &Unit) const;
1225
Frederic Riss63786b02015-03-15 20:45:43 +00001226 /// \brief Extract the line tables fromt he original dwarf, extract
1227 /// the relevant parts according to the linked function ranges and
1228 /// emit the result in the debug_line section.
1229 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1230
Frederic Rissbce93ff2015-03-16 02:05:10 +00001231 /// \brief Emit the accelerator entries for \p Unit.
1232 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1233
Frederic Riss5a642072015-06-05 23:06:11 +00001234 /// \brief Patch the frame info for an object file and emit it.
1235 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1236 unsigned AddressSize);
1237
Frederic Rissb8b43d52015-03-04 22:07:44 +00001238 /// \brief DIELoc objects that need to be destructed (but not freed!).
1239 std::vector<DIELoc *> DIELocs;
1240 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1241 std::vector<DIEBlock *> DIEBlocks;
1242 /// \brief Allocator used for all the DIEValue objects.
1243 BumpPtrAllocator DIEAlloc;
1244 /// @}
1245
Frederic Riss1b9da422015-02-13 23:18:29 +00001246 /// \defgroup Helpers Various helper methods.
1247 ///
1248 /// @{
1249 const DWARFDebugInfoEntryMinimal *
1250 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1251 const DWARFDebugInfoEntryMinimal &DIE,
1252 CompileUnit *&ReferencedCU);
1253
1254 CompileUnit *getUnitForOffset(unsigned Offset);
1255
Frederic Rissbce93ff2015-03-16 02:05:10 +00001256 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1257 AttributesInfo &Info);
1258
Frederic Riss1b9da422015-02-13 23:18:29 +00001259 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001260 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001261
1262 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +00001263 /// @}
1264
Frederic Riss563cba62015-01-28 22:15:14 +00001265private:
Frederic Rissd3455182015-01-28 18:27:01 +00001266 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001267 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001268 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001269 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001270
1271 /// The units of the current debug map object.
1272 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001273
1274 /// The debug map object curently under consideration.
1275 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001276
1277 /// \brief The Dwarf string pool
1278 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001279
1280 /// \brief This map is keyed by the entry PC of functions in that
1281 /// debug object and the associated value is a pair storing the
1282 /// corresponding end PC and the offset to apply to get the linked
1283 /// address.
1284 ///
1285 /// See startDebugObject() for a more complete description of its use.
1286 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001287
1288 /// \brief The CIEs that have been emitted in the output
1289 /// section. The actual CIE data serves a the key to this StringMap,
1290 /// this takes care of comparing the semantics of CIEs defined in
1291 /// different object files.
1292 StringMap<uint32_t> EmittedCIEs;
1293
1294 /// Offset of the last CIE that has been emitted in the output
1295 /// debug_frame section.
1296 uint32_t LastCIEOffset;
Frederic Rissd3455182015-01-28 18:27:01 +00001297};
1298
Frederic Riss1b9da422015-02-13 23:18:29 +00001299/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1300/// returning our CompileUnit object instead.
1301CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1302 auto CU =
1303 std::upper_bound(Units.begin(), Units.end(), Offset,
1304 [](uint32_t LHS, const CompileUnit &RHS) {
1305 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1306 });
1307 return CU != Units.end() ? &*CU : nullptr;
1308}
1309
1310/// \brief Resolve the DIE attribute reference that has been
1311/// extracted in \p RefValue. The resulting DIE migh be in another
1312/// CompileUnit which is stored into \p ReferencedCU.
1313/// \returns null if resolving fails for any reason.
1314const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1315 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1316 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1317 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1318 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1319
1320 if ((RefCU = getUnitForOffset(RefOffset)))
1321 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1322 return RefDie;
1323
1324 reportWarning("could not find referenced DIE", &Unit, &DIE);
1325 return nullptr;
1326}
1327
Frederic Rissbce93ff2015-03-16 02:05:10 +00001328/// \brief Get the potential name and mangled name for the entity
1329/// described by \p Die and store them in \Info if they are not
1330/// already there.
1331/// \returns is a name was found.
1332bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1333 DWARFUnit &U, AttributesInfo &Info) {
1334 // FIXME: a bit wastefull as the first getName might return the
1335 // short name.
1336 if (!Info.MangledName &&
1337 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1338 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1339
1340 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1341 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1342
1343 return Info.Name || Info.MangledName;
1344}
1345
Frederic Riss1b9da422015-02-13 23:18:29 +00001346/// \brief Report a warning to the user, optionaly including
1347/// information about a specific \p DIE related to the warning.
1348void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001349 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001350 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001351 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001352 Context = CurrentDebugObject->getObjectFilename();
1353 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001354
Frederic Rissb9818322015-02-28 00:29:07 +00001355 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001356 return;
1357
1358 errs() << " in DIE:\n";
1359 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1360 6 /* Indent */);
1361}
1362
Frederic Rissc99ea202015-02-28 00:29:11 +00001363bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1364 if (Options.NoOutput)
1365 return true;
1366
Frederic Rissb52cf522015-02-28 00:42:37 +00001367 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001368 return Streamer->init(TheTriple, OutputFilename);
1369}
1370
Frederic Riss563cba62015-01-28 22:15:14 +00001371/// \brief Recursive helper to gather the child->parent relationships in the
1372/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001373static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1374 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +00001375 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1376 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1377
1378 if (DIE->hasChildren())
1379 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1380 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +00001381 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +00001382}
1383
Frederic Riss84c09a52015-02-13 23:18:34 +00001384static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1385 switch (Tag) {
1386 default:
1387 return false;
1388 case dwarf::DW_TAG_subprogram:
1389 case dwarf::DW_TAG_lexical_block:
1390 case dwarf::DW_TAG_subroutine_type:
1391 case dwarf::DW_TAG_structure_type:
1392 case dwarf::DW_TAG_class_type:
1393 case dwarf::DW_TAG_union_type:
1394 return true;
1395 }
1396 llvm_unreachable("Invalid Tag");
1397}
1398
Frederic Riss63786b02015-03-15 20:45:43 +00001399void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001400 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001401 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001402 // Iterate over the debug map entries and put all the ones that are
1403 // functions (because they have a size) into the Ranges map. This
1404 // map is very similar to the FunctionRanges that are stored in each
1405 // unit, with 2 notable differences:
1406 // - obviously this one is global, while the other ones are per-unit.
1407 // - this one contains not only the functions described in the DIE
1408 // tree, but also the ones that are only in the debug map.
1409 // The latter information is required to reproduce dsymutil's logic
1410 // while linking line tables. The cases where this information
1411 // matters look like bugs that need to be investigated, but for now
1412 // we need to reproduce dsymutil's behavior.
1413 // FIXME: Once we understood exactly if that information is needed,
1414 // maybe totally remove this (or try to use it to do a real
1415 // -gline-tables-only on Darwin.
1416 for (const auto &Entry : Obj.symbols()) {
1417 const auto &Mapping = Entry.getValue();
1418 if (Mapping.Size)
1419 Ranges[Mapping.ObjectAddress] = std::make_pair(
1420 Mapping.ObjectAddress + Mapping.Size,
1421 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1422 }
Frederic Riss563cba62015-01-28 22:15:14 +00001423}
1424
Frederic Riss1036e642015-02-13 23:18:22 +00001425void DwarfLinker::endDebugObject() {
1426 Units.clear();
1427 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001428 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001429
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001430 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1431 (*I)->~DIEBlock();
1432 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1433 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001434
1435 DIEBlocks.clear();
1436 DIELocs.clear();
1437 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001438}
1439
1440/// \brief Iterate over the relocations of the given \p Section and
1441/// store the ones that correspond to debug map entries into the
1442/// ValidRelocs array.
1443void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1444 const object::MachOObjectFile &Obj,
1445 const DebugMapObject &DMO) {
1446 StringRef Contents;
1447 Section.getContents(Contents);
1448 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1449
1450 for (const object::RelocationRef &Reloc : Section.relocations()) {
1451 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1452 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1453 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001454 uint64_t Offset64 = Reloc.getOffset();
1455 if ((RelocSize != 4 && RelocSize != 8)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001456 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001457 continue;
1458 }
1459 uint32_t Offset = Offset64;
1460 // Mach-o uses REL relocations, the addend is at the relocation offset.
1461 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1462
1463 auto Sym = Reloc.getSymbol();
1464 if (Sym != Obj.symbol_end()) {
1465 StringRef SymbolName;
1466 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001467 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001468 continue;
1469 }
1470 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1471 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1472 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1473 // Do not store the addend. The addend was the address of the
1474 // symbol in the object file, the address in the binary that is
1475 // stored in the debug map doesn't need to be offseted.
1476 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1477 }
1478 }
1479}
1480
1481/// \brief Dispatch the valid relocation finding logic to the
1482/// appropriate handler depending on the object file format.
1483bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1484 const object::ObjectFile &Obj,
1485 const DebugMapObject &DMO) {
1486 // Dispatch to the right handler depending on the file type.
1487 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1488 findValidRelocsMachO(Section, *MachOObj, DMO);
1489 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001490 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001491
1492 if (ValidRelocs.empty())
1493 return false;
1494
1495 // Sort the relocations by offset. We will walk the DIEs linearly in
1496 // the file, this allows us to just keep an index in the relocation
1497 // array that we advance during our walk, rather than resorting to
1498 // some associative container. See DwarfLinker::NextValidReloc.
1499 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1500 return true;
1501}
1502
1503/// \brief Look for relocations in the debug_info section that match
1504/// entries in the debug map. These relocations will drive the Dwarf
1505/// link by indicating which DIEs refer to symbols present in the
1506/// linked binary.
1507/// \returns wether there are any valid relocations in the debug info.
1508bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1509 const DebugMapObject &DMO) {
1510 // Find the debug_info section.
1511 for (const object::SectionRef &Section : Obj.sections()) {
1512 StringRef SectionName;
1513 Section.getName(SectionName);
1514 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1515 if (SectionName != "debug_info")
1516 continue;
1517 return findValidRelocs(Section, Obj, DMO);
1518 }
1519 return false;
1520}
Frederic Riss563cba62015-01-28 22:15:14 +00001521
Frederic Riss84c09a52015-02-13 23:18:34 +00001522/// \brief Checks that there is a relocation against an actual debug
1523/// map entry between \p StartOffset and \p NextOffset.
1524///
1525/// This function must be called with offsets in strictly ascending
1526/// order because it never looks back at relocations it already 'went past'.
1527/// \returns true and sets Info.InDebugMap if it is the case.
1528bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1529 CompileUnit::DIEInfo &Info) {
1530 assert(NextValidReloc == 0 ||
1531 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1532 if (NextValidReloc >= ValidRelocs.size())
1533 return false;
1534
1535 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1536
1537 // We might need to skip some relocs that we didn't consider. For
1538 // example the high_pc of a discarded DIE might contain a reloc that
1539 // is in the list because it actually corresponds to the start of a
1540 // function that is in the debug map.
1541 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1542 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1543
1544 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1545 return false;
1546
1547 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001548 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissb9818322015-02-28 00:29:07 +00001549 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001550 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1551 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001552 uint64_t(Mapping.ObjectAddress),
1553 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001554
Frederic Rissf37964c2015-06-05 20:27:07 +00001555 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1556 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001557 Info.InDebugMap = true;
1558 return true;
1559}
1560
1561/// \brief Get the starting and ending (exclusive) offset for the
1562/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1563/// supposed to point to the position of the first attribute described
1564/// by \p Abbrev.
1565/// \return [StartOffset, EndOffset) as a pair.
1566static std::pair<uint32_t, uint32_t>
1567getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1568 unsigned Offset, const DWARFUnit &Unit) {
1569 DataExtractor Data = Unit.getDebugInfoExtractor();
1570
1571 for (unsigned i = 0; i < Idx; ++i)
1572 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1573
1574 uint32_t End = Offset;
1575 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1576
1577 return std::make_pair(Offset, End);
1578}
1579
1580/// \brief Check if a variable describing DIE should be kept.
1581/// \returns updated TraversalFlags.
1582unsigned DwarfLinker::shouldKeepVariableDIE(
1583 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1584 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1585 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1586
1587 // Global variables with constant value can always be kept.
1588 if (!(Flags & TF_InFunctionScope) &&
1589 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1590 MyInfo.InDebugMap = true;
1591 return Flags | TF_Keep;
1592 }
1593
1594 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1595 if (LocationIdx == -1U)
1596 return Flags;
1597
1598 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1599 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1600 uint32_t LocationOffset, LocationEndOffset;
1601 std::tie(LocationOffset, LocationEndOffset) =
1602 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1603
1604 // See if there is a relocation to a valid debug map entry inside
1605 // this variable's location. The order is important here. We want to
1606 // always check in the variable has a valid relocation, so that the
1607 // DIEInfo is filled. However, we don't want a static variable in a
1608 // function to force us to keep the enclosing function.
1609 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1610 (Flags & TF_InFunctionScope))
1611 return Flags;
1612
Frederic Rissb9818322015-02-28 00:29:07 +00001613 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001614 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1615
1616 return Flags | TF_Keep;
1617}
1618
1619/// \brief Check if a function describing DIE should be kept.
1620/// \returns updated TraversalFlags.
1621unsigned DwarfLinker::shouldKeepSubprogramDIE(
1622 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1623 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1624 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1625
1626 Flags |= TF_InFunctionScope;
1627
1628 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1629 if (LowPcIdx == -1U)
1630 return Flags;
1631
1632 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1633 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1634 uint32_t LowPcOffset, LowPcEndOffset;
1635 std::tie(LowPcOffset, LowPcEndOffset) =
1636 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1637
1638 uint64_t LowPc =
1639 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1640 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1641 if (LowPc == -1ULL ||
1642 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1643 return Flags;
1644
Frederic Rissb9818322015-02-28 00:29:07 +00001645 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001646 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1647
Frederic Riss1af75f72015-03-12 18:45:10 +00001648 Flags |= TF_Keep;
1649
1650 DWARFFormValue HighPcValue;
1651 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1652 reportWarning("Function without high_pc. Range will be discarded.\n",
1653 &OrigUnit, &DIE);
1654 return Flags;
1655 }
1656
1657 uint64_t HighPc;
1658 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1659 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1660 } else {
1661 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1662 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1663 }
1664
Frederic Riss63786b02015-03-15 20:45:43 +00001665 // Replace the debug map range with a more accurate one.
1666 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001667 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1668 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001669}
1670
1671/// \brief Check if a DIE should be kept.
1672/// \returns updated TraversalFlags.
1673unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1674 CompileUnit &Unit,
1675 CompileUnit::DIEInfo &MyInfo,
1676 unsigned Flags) {
1677 switch (DIE.getTag()) {
1678 case dwarf::DW_TAG_constant:
1679 case dwarf::DW_TAG_variable:
1680 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1681 case dwarf::DW_TAG_subprogram:
1682 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1683 case dwarf::DW_TAG_module:
1684 case dwarf::DW_TAG_imported_module:
1685 case dwarf::DW_TAG_imported_declaration:
1686 case dwarf::DW_TAG_imported_unit:
1687 // We always want to keep these.
1688 return Flags | TF_Keep;
1689 }
1690
1691 return Flags;
1692}
1693
Frederic Riss84c09a52015-02-13 23:18:34 +00001694/// \brief Mark the passed DIE as well as all the ones it depends on
1695/// as kept.
1696///
1697/// This function is called by lookForDIEsToKeep on DIEs that are
1698/// newly discovered to be needed in the link. It recursively calls
1699/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1700/// TraversalFlags to inform it that it's not doing the primary DIE
1701/// tree walk.
1702void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1703 CompileUnit::DIEInfo &MyInfo,
1704 const DebugMapObject &DMO,
1705 CompileUnit &CU, unsigned Flags) {
1706 const DWARFUnit &Unit = CU.getOrigUnit();
1707 MyInfo.Keep = true;
1708
1709 // First mark all the parent chain as kept.
1710 unsigned AncestorIdx = MyInfo.ParentIdx;
1711 while (!CU.getInfo(AncestorIdx).Keep) {
1712 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1713 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1714 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1715 }
1716
1717 // Then we need to mark all the DIEs referenced by this DIE's
1718 // attributes as kept.
1719 DataExtractor Data = Unit.getDebugInfoExtractor();
1720 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1721 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1722
1723 // Mark all DIEs referenced through atttributes as kept.
1724 for (const auto &AttrSpec : Abbrev->attributes()) {
1725 DWARFFormValue Val(AttrSpec.Form);
1726
1727 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1728 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1729 continue;
1730 }
1731
1732 Val.extractValue(Data, &Offset, &Unit);
1733 CompileUnit *ReferencedCU;
1734 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1735 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1736 TF_Keep | TF_DependencyWalk);
1737 }
1738}
1739
1740/// \brief Recursively walk the \p DIE tree and look for DIEs to
1741/// keep. Store that information in \p CU's DIEInfo.
1742///
1743/// This function is the entry point of the DIE selection
1744/// algorithm. It is expected to walk the DIE tree in file order and
1745/// (though the mediation of its helper) call hasValidRelocation() on
1746/// each DIE that might be a 'root DIE' (See DwarfLinker class
1747/// comment).
1748/// While walking the dependencies of root DIEs, this function is
1749/// also called, but during these dependency walks the file order is
1750/// not respected. The TF_DependencyWalk flag tells us which kind of
1751/// traversal we are currently doing.
1752void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1753 const DebugMapObject &DMO, CompileUnit &CU,
1754 unsigned Flags) {
1755 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1756 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1757 bool AlreadyKept = MyInfo.Keep;
1758
1759 // If the Keep flag is set, we are marking a required DIE's
1760 // dependencies. If our target is already marked as kept, we're all
1761 // set.
1762 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1763 return;
1764
1765 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1766 // because it would screw up the relocation finding logic.
1767 if (!(Flags & TF_DependencyWalk))
1768 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1769
1770 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1771 if (!AlreadyKept && (Flags & TF_Keep))
1772 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1773
1774 // The TF_ParentWalk flag tells us that we are currently walking up
1775 // the parent chain of a required DIE, and we don't want to mark all
1776 // the children of the parents as kept (consider for example a
1777 // DW_TAG_namespace node in the parent chain). There are however a
1778 // set of DIE types for which we want to ignore that directive and still
1779 // walk their children.
1780 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1781 Flags &= ~TF_ParentWalk;
1782
1783 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1784 return;
1785
1786 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1787 Child = Child->getSibling())
1788 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1789}
1790
Frederic Rissb8b43d52015-03-04 22:07:44 +00001791/// \brief Assign an abbreviation numer to \p Abbrev.
1792///
1793/// Our DIEs get freed after every DebugMapObject has been processed,
1794/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1795/// the instances hold by the DIEs. When we encounter an abbreviation
1796/// that we don't know, we create a permanent copy of it.
1797void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1798 // Check the set for priors.
1799 FoldingSetNodeID ID;
1800 Abbrev.Profile(ID);
1801 void *InsertToken;
1802 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1803
1804 // If it's newly added.
1805 if (InSet) {
1806 // Assign existing abbreviation number.
1807 Abbrev.setNumber(InSet->getNumber());
1808 } else {
1809 // Add to abbreviation list.
1810 Abbreviations.push_back(
1811 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1812 for (const auto &Attr : Abbrev.getData())
1813 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1814 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1815 // Assign the unique abbreviation number.
1816 Abbrev.setNumber(Abbreviations.size());
1817 Abbreviations.back()->setNumber(Abbreviations.size());
1818 }
1819}
1820
1821/// \brief Clone a string attribute described by \p AttrSpec and add
1822/// it to \p Die.
1823/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001824unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1825 const DWARFFormValue &Val,
1826 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001827 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001828 const char *String = *Val.getAsCString(&U);
1829 unsigned Offset = StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00001830 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001831 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001832 return 4;
1833}
1834
1835/// \brief Clone an attribute referencing another DIE and add
1836/// it to \p Die.
1837/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001838unsigned DwarfLinker::cloneDieReferenceAttribute(
1839 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1840 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001841 CompileUnit &Unit) {
1842 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
Frederic Riss9833de62015-03-06 23:22:53 +00001843 DIE *NewRefDie = nullptr;
1844 CompileUnit *RefUnit = nullptr;
1845 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1846
1847 if (!(RefUnit = getUnitForOffset(Ref)) ||
1848 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1849 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1850 if (!AttributeString)
1851 AttributeString = "DW_AT_???";
1852 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1853 ". Dropping.",
Frederic Riss6afcfce2015-03-13 18:35:57 +00001854 &Unit.getOrigUnit(), &InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001855 return 0;
1856 }
1857
1858 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1859 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1860 if (!RefInfo.Clone) {
1861 assert(Ref > InputDIE.getOffset());
1862 // We haven't cloned this DIE yet. Just create an empty one and
1863 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00001864 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00001865 }
1866 NewRefDie = RefInfo.Clone;
1867
1868 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1869 // We cannot currently rely on a DIEEntry to emit ref_addr
1870 // references, because the implementation calls back to DwarfDebug
1871 // to find the unit offset. (We don't have a DwarfDebug)
1872 // FIXME: we should be able to design DIEEntry reliance on
1873 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001874 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00001875 if (Ref < InputDIE.getOffset()) {
1876 // We must have already cloned that DIE.
1877 uint32_t NewRefOffset =
1878 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001879 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00001880 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1881 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00001882 } else {
1883 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001884 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00001885 Unit.noteForwardReference(
1886 NewRefDie, RefUnit,
1887 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1888 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00001889 }
Frederic Riss9833de62015-03-06 23:22:53 +00001890 return AttrSize;
1891 }
1892
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00001893 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1894 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001895 return AttrSize;
1896}
1897
1898/// \brief Clone an attribute of block form (locations, constants) and add
1899/// it to \p Die.
1900/// \returns the size of the new attribute.
1901unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1902 const DWARFFormValue &Val,
1903 unsigned AttrSize) {
1904 DIE *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001905 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001906 DIELoc *Loc = nullptr;
1907 DIEBlock *Block = nullptr;
1908 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001909 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001910 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001911 DIELocs.push_back(Loc);
1912 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001913 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001914 DIEBlocks.push_back(Block);
1915 }
1916 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00001917
1918 if (Loc)
1919 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1920 dwarf::Form(AttrSpec.Form), Loc);
1921 else
1922 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1923 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001924 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1925 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00001926 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1927 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001928 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1929 // the DIE class, this if could be replaced by
1930 // Attr->setSize(Bytes.size()).
1931 if (Streamer) {
1932 if (Loc)
1933 Loc->ComputeSize(&Streamer->getAsmPrinter());
1934 else
1935 Block->ComputeSize(&Streamer->getAsmPrinter());
1936 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00001937 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001938 return AttrSize;
1939}
1940
Frederic Riss31da3242015-03-11 18:45:52 +00001941/// \brief Clone an address attribute and add it to \p Die.
1942/// \returns the size of the new attribute.
1943unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1944 const DWARFFormValue &Val,
1945 const CompileUnit &Unit,
1946 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001947 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00001948 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1949 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1950 Die.getTag() == dwarf::DW_TAG_lexical_block)
1951 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001952 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1953 Addr = Unit.getLowPc();
1954 if (Addr == UINT64_MAX)
1955 return 0;
1956 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00001957 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00001958 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001959 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1960 if (uint64_t HighPc = Unit.getHighPc())
1961 Addr = HighPc;
1962 else
1963 return 0;
1964 } else
1965 // If we have a high_pc recorded for the input DIE, use
1966 // it. Otherwise (when no relocations where applied) just use the
1967 // one we just decoded.
1968 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00001969 }
1970
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00001971 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001972 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00001973 return Unit.getOrigUnit().getAddressByteSize();
1974}
1975
Frederic Rissb8b43d52015-03-04 22:07:44 +00001976/// \brief Clone a scalar attribute and add it to \p Die.
1977/// \returns the size of the new attribute.
1978unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00001979 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00001980 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001981 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001982 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001983 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1984 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1985 if (Unit.getLowPc() == -1ULL)
1986 return 0;
1987 // Dwarf >= 4 high_pc is an size, not an address.
1988 Value = Unit.getHighPc() - Unit.getLowPc();
1989 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00001990 Value = *Val.getAsSectionOffset();
1991 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1992 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001993 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1994 Value = *OptionalValue;
1995 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001996 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1997 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001998 return 0;
1999 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002000 PatchLocation Patch =
2001 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2002 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002003 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002004 Unit.noteRangeAttribute(Die, Patch);
Frederic Rissdfb97902015-03-14 15:49:07 +00002005 // A more generic way to check for location attributes would be
2006 // nice, but it's very unlikely that any other attribute needs a
2007 // location list.
2008 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2009 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002010 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002011 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2012 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002013
Frederic Rissb8b43d52015-03-04 22:07:44 +00002014 return AttrSize;
2015}
2016
2017/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2018/// value \p Val, and add it to \p Die.
2019/// \returns the size of the cloned attribute.
2020unsigned DwarfLinker::cloneAttribute(DIE &Die,
2021 const DWARFDebugInfoEntryMinimal &InputDIE,
2022 CompileUnit &Unit,
2023 const DWARFFormValue &Val,
2024 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00002025 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002026 const DWARFUnit &U = Unit.getOrigUnit();
2027
2028 switch (AttrSpec.Form) {
2029 case dwarf::DW_FORM_strp:
2030 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002031 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002032 case dwarf::DW_FORM_ref_addr:
2033 case dwarf::DW_FORM_ref1:
2034 case dwarf::DW_FORM_ref2:
2035 case dwarf::DW_FORM_ref4:
2036 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002037 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002038 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002039 case dwarf::DW_FORM_block:
2040 case dwarf::DW_FORM_block1:
2041 case dwarf::DW_FORM_block2:
2042 case dwarf::DW_FORM_block4:
2043 case dwarf::DW_FORM_exprloc:
2044 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2045 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002046 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002047 case dwarf::DW_FORM_data1:
2048 case dwarf::DW_FORM_data2:
2049 case dwarf::DW_FORM_data4:
2050 case dwarf::DW_FORM_data8:
2051 case dwarf::DW_FORM_udata:
2052 case dwarf::DW_FORM_sdata:
2053 case dwarf::DW_FORM_sec_offset:
2054 case dwarf::DW_FORM_flag:
2055 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002056 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2057 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002058 default:
2059 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2060 &InputDIE);
2061 }
2062
2063 return 0;
2064}
2065
Frederic Riss23e20e92015-03-07 01:25:09 +00002066/// \brief Apply the valid relocations found by findValidRelocs() to
2067/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2068/// in the debug_info section.
2069///
2070/// Like for findValidRelocs(), this function must be called with
2071/// monotonic \p BaseOffset values.
2072///
2073/// \returns wether any reloc has been applied.
2074bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2075 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002076 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002077 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2078 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002079 if (NextValidReloc >= ValidRelocs.size())
2080 return false;
2081
2082 // Skip relocs that haven't been applied.
2083 while (NextValidReloc < ValidRelocs.size() &&
2084 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2085 ++NextValidReloc;
2086
2087 bool Applied = false;
2088 uint64_t EndOffset = BaseOffset + Data.size();
2089 while (NextValidReloc < ValidRelocs.size() &&
2090 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2091 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2092 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2093 assert(ValidReloc.Offset - BaseOffset < Data.size());
2094 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2095 char Buf[8];
2096 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2097 Value += ValidReloc.Addend;
2098 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2099 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2100 Buf[i] = uint8_t(Value >> (Index * 8));
2101 }
2102 assert(ValidReloc.Size <= sizeof(Buf));
2103 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2104 Applied = true;
2105 }
2106
2107 return Applied;
2108}
2109
Frederic Rissbce93ff2015-03-16 02:05:10 +00002110static bool isTypeTag(uint16_t Tag) {
2111 switch (Tag) {
2112 case dwarf::DW_TAG_array_type:
2113 case dwarf::DW_TAG_class_type:
2114 case dwarf::DW_TAG_enumeration_type:
2115 case dwarf::DW_TAG_pointer_type:
2116 case dwarf::DW_TAG_reference_type:
2117 case dwarf::DW_TAG_string_type:
2118 case dwarf::DW_TAG_structure_type:
2119 case dwarf::DW_TAG_subroutine_type:
2120 case dwarf::DW_TAG_typedef:
2121 case dwarf::DW_TAG_union_type:
2122 case dwarf::DW_TAG_ptr_to_member_type:
2123 case dwarf::DW_TAG_set_type:
2124 case dwarf::DW_TAG_subrange_type:
2125 case dwarf::DW_TAG_base_type:
2126 case dwarf::DW_TAG_const_type:
2127 case dwarf::DW_TAG_constant:
2128 case dwarf::DW_TAG_file_type:
2129 case dwarf::DW_TAG_namelist:
2130 case dwarf::DW_TAG_packed_type:
2131 case dwarf::DW_TAG_volatile_type:
2132 case dwarf::DW_TAG_restrict_type:
2133 case dwarf::DW_TAG_interface_type:
2134 case dwarf::DW_TAG_unspecified_type:
2135 case dwarf::DW_TAG_shared_type:
2136 return true;
2137 default:
2138 break;
2139 }
2140 return false;
2141}
2142
Frederic Rissb8b43d52015-03-04 22:07:44 +00002143/// \brief Recursively clone \p InputDIE's subtrees that have been
2144/// selected to appear in the linked output.
2145///
2146/// \param OutOffset is the Offset where the newly created DIE will
2147/// lie in the linked compile unit.
2148///
2149/// \returns the cloned DIE object or null if nothing was selected.
2150DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002151 CompileUnit &Unit, int64_t PCOffset,
2152 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002153 DWARFUnit &U = Unit.getOrigUnit();
2154 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002155 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002156
2157 // Should the DIE appear in the output?
2158 if (!Unit.getInfo(Idx).Keep)
2159 return nullptr;
2160
2161 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002162 // The DIE might have been already created by a forward reference
2163 // (see cloneDieReferenceAttribute()).
2164 DIE *Die = Info.Clone;
2165 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002166 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002167 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002168 Die->setOffset(OutOffset);
2169
2170 // Extract and clone every attribute.
2171 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002172 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002173 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002174
2175 // We could copy the data only if we need to aply a relocation to
2176 // it. After testing, it seems there is no performance downside to
2177 // doing the copy unconditionally, and it makes the code simpler.
2178 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2179 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2180 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002181 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2182 // If we applied relocations, we store the value of high_pc that was
2183 // potentially stored in the input DIE. If high_pc is an address
2184 // (Dwarf version == 2), then it might have been relocated to a
2185 // totally unrelated value (because the end address in the object
2186 // file might be start address of another function which got moved
2187 // independantly by the linker). The computation of the actual
2188 // high_pc value is done in cloneAddressAttribute().
2189 AttrInfo.OrigHighPc =
2190 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2191 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002192
2193 // Reset the Offset to 0 as we will be working on the local copy of
2194 // the data.
2195 Offset = 0;
2196
Frederic Rissb8b43d52015-03-04 22:07:44 +00002197 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2198 Offset += getULEB128Size(Abbrev->getCode());
2199
Frederic Riss31da3242015-03-11 18:45:52 +00002200 // We are entering a subprogram. Get and propagate the PCOffset.
2201 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2202 PCOffset = Info.AddrAdjust;
2203 AttrInfo.PCOffset = PCOffset;
2204
Frederic Rissb8b43d52015-03-04 22:07:44 +00002205 for (const auto &AttrSpec : Abbrev->attributes()) {
2206 DWARFFormValue Val(AttrSpec.Form);
2207 uint32_t AttrSize = Offset;
2208 Val.extractValue(Data, &Offset, &U);
2209 AttrSize = Offset - AttrSize;
2210
Frederic Riss31da3242015-03-11 18:45:52 +00002211 OutOffset +=
2212 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002213 }
2214
Frederic Rissbce93ff2015-03-16 02:05:10 +00002215 // Look for accelerator entries.
2216 uint16_t Tag = InputDIE.getTag();
2217 // FIXME: This is slightly wrong. An inline_subroutine without a
2218 // low_pc, but with AT_ranges might be interesting to get into the
2219 // accelerator tables too. For now stick with dsymutil's behavior.
2220 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2221 Tag != dwarf::DW_TAG_compile_unit &&
2222 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2223 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2224 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2225 AttrInfo.MangledNameOffset,
2226 Tag == dwarf::DW_TAG_inlined_subroutine);
2227 if (AttrInfo.Name)
2228 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2229 Tag == dwarf::DW_TAG_inlined_subroutine);
2230 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2231 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2232 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2233 }
2234
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002235 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002236 // If a scope DIE is kept, we must have kept at least one child. If
2237 // it's not the case, we'll just be emitting one wasteful end of
2238 // children marker, but things won't break.
2239 if (InputDIE.hasChildren())
2240 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2241 // Assign a permanent abbrev number
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002242 AssignAbbrev(NewAbbrev);
2243 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002244
2245 // Add the size of the abbreviation number to the output offset.
2246 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2247
2248 if (!Abbrev->hasChildren()) {
2249 // Update our size.
2250 Die->setSize(OutOffset - Die->getOffset());
2251 return Die;
2252 }
2253
2254 // Recursively clone children.
2255 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2256 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002257 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002258 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002259 OutOffset = Clone->getOffset() + Clone->getSize();
2260 }
2261 }
2262
2263 // Account for the end of children marker.
2264 OutOffset += sizeof(int8_t);
2265 // Update our size.
2266 Die->setSize(OutOffset - Die->getOffset());
2267 return Die;
2268}
2269
Frederic Riss25440872015-03-13 23:30:31 +00002270/// \brief Patch the input object file relevant debug_ranges entries
2271/// and emit them in the output file. Update the relevant attributes
2272/// to point at the new entries.
2273void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2274 DWARFContext &OrigDwarf) const {
2275 DWARFDebugRangeList RangeList;
2276 const auto &FunctionRanges = Unit.getFunctionRanges();
2277 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2278 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2279 OrigDwarf.isLittleEndian(), AddressSize);
2280 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2281 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002282 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002283 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2284 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2285 // Ranges addresses are based on the unit's low_pc. Compute the
2286 // offset we need to apply to adapt to the the new unit's low_pc.
2287 int64_t UnitPcOffset = 0;
2288 if (OrigLowPc != -1ULL)
2289 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2290
2291 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002292 uint32_t Offset = RangeAttribute.get();
2293 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002294 RangeList.extract(RangeExtractor, &Offset);
2295 const auto &Entries = RangeList.getEntries();
2296 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2297
2298 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2299 First.StartAddress >= CurrRange.stop()) {
2300 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2301 if (CurrRange == InvalidRange ||
2302 CurrRange.start() > First.StartAddress + OrigLowPc) {
2303 reportWarning("no mapping for range.");
2304 continue;
2305 }
2306 }
2307
2308 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2309 AddressSize);
2310 }
2311}
2312
Frederic Riss563b1b02015-03-14 03:46:51 +00002313/// \brief Generate the debug_aranges entries for \p Unit and if the
2314/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2315/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002316/// FIXME: this could actually be done right in patchRangesForUnit,
2317/// but for the sake of initial bit-for-bit compatibility with legacy
2318/// dsymutil, we have to do it in a delayed pass.
2319void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002320 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002321 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002322 Attr->set(Streamer->getRangesSectionSize());
2323 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002324}
2325
Frederic Riss63786b02015-03-15 20:45:43 +00002326/// \brief Insert the new line info sequence \p Seq into the current
2327/// set of already linked line info \p Rows.
2328static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2329 std::vector<DWARFDebugLine::Row> &Rows) {
2330 if (Seq.empty())
2331 return;
2332
2333 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2334 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2335 Seq.clear();
2336 return;
2337 }
2338
2339 auto InsertPoint = std::lower_bound(
2340 Rows.begin(), Rows.end(), Seq.front(),
2341 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2342 return LHS.Address < RHS.Address;
2343 });
2344
2345 // FIXME: this only removes the unneeded end_sequence if the
2346 // sequences have been inserted in order. using a global sort like
2347 // described in patchLineTableForUnit() and delaying the end_sequene
2348 // elimination to emitLineTableForUnit() we can get rid of all of them.
2349 if (InsertPoint != Rows.end() &&
2350 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2351 *InsertPoint = Seq.front();
2352 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2353 } else {
2354 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2355 }
2356
2357 Seq.clear();
2358}
2359
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002360static void patchStmtList(DIE &Die, DIEInteger Offset) {
2361 for (auto &V : Die.values())
2362 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002363 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002364 return;
2365 }
2366
2367 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2368}
2369
Frederic Riss63786b02015-03-15 20:45:43 +00002370/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2371/// recreate a relocated version of these for the address ranges that
2372/// are present in the binary.
2373void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2374 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002375 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002376 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2377 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2378 if (StmtList == -1ULL)
2379 return;
2380
2381 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002382 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2383 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002384
2385 // Parse the original line info for the unit.
2386 DWARFDebugLine::LineTable LineTable;
2387 uint32_t StmtOffset = StmtList;
2388 StringRef LineData = OrigDwarf.getLineSection().Data;
2389 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2390 Unit.getOrigUnit().getAddressByteSize());
2391 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2392 &StmtOffset);
2393
2394 // This vector is the output line table.
2395 std::vector<DWARFDebugLine::Row> NewRows;
2396 NewRows.reserve(LineTable.Rows.size());
2397
2398 // Current sequence of rows being extracted, before being inserted
2399 // in NewRows.
2400 std::vector<DWARFDebugLine::Row> Seq;
2401 const auto &FunctionRanges = Unit.getFunctionRanges();
2402 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2403
2404 // FIXME: This logic is meant to generate exactly the same output as
2405 // Darwin's classic dsynutil. There is a nicer way to implement this
2406 // by simply putting all the relocated line info in NewRows and simply
2407 // sorting NewRows before passing it to emitLineTableForUnit. This
2408 // should be correct as sequences for a function should stay
2409 // together in the sorted output. There are a few corner cases that
2410 // look suspicious though, and that required to implement the logic
2411 // this way. Revisit that once initial validation is finished.
2412
2413 // Iterate over the object file line info and extract the sequences
2414 // that correspond to linked functions.
2415 for (auto &Row : LineTable.Rows) {
2416 // Check wether we stepped out of the range. The range is
2417 // half-open, but consider accept the end address of the range if
2418 // it is marked as end_sequence in the input (because in that
2419 // case, the relocation offset is accurate and that entry won't
2420 // serve as the start of another function).
2421 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2422 Row.Address > CurrRange.stop() ||
2423 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2424 // We just stepped out of a known range. Insert a end_sequence
2425 // corresponding to the end of the range.
2426 uint64_t StopAddress = CurrRange != InvalidRange
2427 ? CurrRange.stop() + CurrRange.value()
2428 : -1ULL;
2429 CurrRange = FunctionRanges.find(Row.Address);
2430 bool CurrRangeValid =
2431 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2432 if (!CurrRangeValid) {
2433 CurrRange = InvalidRange;
2434 if (StopAddress != -1ULL) {
2435 // Try harder by looking in the DebugMapObject function
2436 // ranges map. There are corner cases where this finds a
2437 // valid entry. It's unclear if this is right or wrong, but
2438 // for now do as dsymutil.
2439 // FIXME: Understand exactly what cases this addresses and
2440 // potentially remove it along with the Ranges map.
2441 auto Range = Ranges.lower_bound(Row.Address);
2442 if (Range != Ranges.begin() && Range != Ranges.end())
2443 --Range;
2444
2445 if (Range != Ranges.end() && Range->first <= Row.Address &&
2446 Range->second.first >= Row.Address) {
2447 StopAddress = Row.Address + Range->second.second;
2448 }
2449 }
2450 }
2451 if (StopAddress != -1ULL && !Seq.empty()) {
2452 // Insert end sequence row with the computed end address, but
2453 // the same line as the previous one.
2454 Seq.emplace_back(Seq.back());
2455 Seq.back().Address = StopAddress;
2456 Seq.back().EndSequence = 1;
2457 Seq.back().PrologueEnd = 0;
2458 Seq.back().BasicBlock = 0;
2459 Seq.back().EpilogueBegin = 0;
2460 insertLineSequence(Seq, NewRows);
2461 }
2462
2463 if (!CurrRangeValid)
2464 continue;
2465 }
2466
2467 // Ignore empty sequences.
2468 if (Row.EndSequence && Seq.empty())
2469 continue;
2470
2471 // Relocate row address and add it to the current sequence.
2472 Row.Address += CurrRange.value();
2473 Seq.emplace_back(Row);
2474
2475 if (Row.EndSequence)
2476 insertLineSequence(Seq, NewRows);
2477 }
2478
2479 // Finished extracting, now emit the line tables.
2480 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2481 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2482 // prologue over and that works because we act as both producer and
2483 // consumer. It would be nicer to have a real configurable line
2484 // table emitter.
2485 if (LineTable.Prologue.Version != 2 ||
2486 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2487 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2488 LineTable.Prologue.OpcodeBase != 13)
2489 reportWarning("line table paramters mismatch. Cannot emit.");
2490 else
2491 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2492 LineTable.Prologue.MinInstLength, NewRows,
2493 Unit.getOrigUnit().getAddressByteSize());
2494}
2495
Frederic Rissbce93ff2015-03-16 02:05:10 +00002496void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2497 Streamer->emitPubNamesForUnit(Unit);
2498 Streamer->emitPubTypesForUnit(Unit);
2499}
2500
Frederic Riss5a642072015-06-05 23:06:11 +00002501/// \brief Read the frame info stored in the object, and emit the
2502/// patched frame descriptions for the linked binary.
2503///
2504/// This is actually pretty easy as the data of the CIEs and FDEs can
2505/// be considered as black boxes and moved as is. The only thing to do
2506/// is to patch the addresses in the headers.
2507void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2508 DWARFContext &OrigDwarf,
2509 unsigned AddrSize) {
2510 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2511 if (FrameData.empty())
2512 return;
2513
2514 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2515 uint32_t InputOffset = 0;
2516
2517 // Store the data of the CIEs defined in this object, keyed by their
2518 // offsets.
2519 DenseMap<uint32_t, StringRef> LocalCIES;
2520
2521 while (Data.isValidOffset(InputOffset)) {
2522 uint32_t EntryOffset = InputOffset;
2523 uint32_t InitialLength = Data.getU32(&InputOffset);
2524 if (InitialLength == 0xFFFFFFFF)
2525 return reportWarning("Dwarf64 bits no supported");
2526
2527 uint32_t CIEId = Data.getU32(&InputOffset);
2528 if (CIEId == 0xFFFFFFFF) {
2529 // This is a CIE, store it.
2530 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2531 LocalCIES[EntryOffset] = CIEData;
2532 // The -4 is to account for the CIEId we just read.
2533 InputOffset += InitialLength - 4;
2534 continue;
2535 }
2536
2537 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2538
2539 // Some compilers seem to emit frame info that doesn't start at
2540 // the function entry point, thus we can't just lookup the address
2541 // in the debug map. Use the linker's range map to see if the FDE
2542 // describes something that we can relocate.
2543 auto Range = Ranges.upper_bound(Loc);
2544 if (Range != Ranges.begin())
2545 --Range;
2546 if (Range == Ranges.end() || Range->first > Loc ||
2547 Range->second.first <= Loc) {
2548 // The +4 is to account for the size of the InitialLength field itself.
2549 InputOffset = EntryOffset + InitialLength + 4;
2550 continue;
2551 }
2552
2553 // This is an FDE, and we have a mapping.
2554 // Have we already emitted a corresponding CIE?
2555 StringRef CIEData = LocalCIES[CIEId];
2556 if (CIEData.empty())
2557 return reportWarning("Inconsistent debug_frame content. Dropping.");
2558
2559 // Look if we already emitted a CIE that corresponds to the
2560 // referenced one (the CIE data is the key of that lookup).
2561 auto IteratorInserted = EmittedCIEs.insert(
2562 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2563 // If there is no CIE yet for this ID, emit it.
2564 if (IteratorInserted.second ||
2565 // FIXME: dsymutil-classic only caches the last used CIE for
2566 // reuse. Mimic that behavior for now. Just removing that
2567 // second half of the condition and the LastCIEOffset variable
2568 // makes the code DTRT.
2569 LastCIEOffset != IteratorInserted.first->getValue()) {
2570 LastCIEOffset = Streamer->getFrameSectionSize();
2571 IteratorInserted.first->getValue() = LastCIEOffset;
2572 Streamer->emitCIE(CIEData);
2573 }
2574
2575 // Emit the FDE with updated address and CIE pointer.
2576 // (4 + AddrSize) is the size of the CIEId + initial_location
2577 // fields that will get reconstructed by emitFDE().
2578 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
2579 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
2580 Loc + Range->second.second,
2581 FrameData.substr(InputOffset, FDERemainingBytes));
2582 InputOffset += FDERemainingBytes;
2583 }
2584}
2585
Frederic Rissd3455182015-01-28 18:27:01 +00002586bool DwarfLinker::link(const DebugMap &Map) {
2587
2588 if (Map.begin() == Map.end()) {
2589 errs() << "Empty debug map.\n";
2590 return false;
2591 }
2592
Frederic Rissc99ea202015-02-28 00:29:11 +00002593 if (!createStreamer(Map.getTriple(), OutputFilename))
2594 return false;
2595
Frederic Rissb8b43d52015-03-04 22:07:44 +00002596 // Size of the DIEs (and headers) generated for the linked output.
2597 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002598 // A unique ID that identifies each compile unit.
2599 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002600 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002601 CurrentDebugObject = Obj.get();
2602
Frederic Rissb9818322015-02-28 00:29:07 +00002603 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002604 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2605 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2606 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002607 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00002608 continue;
2609 }
2610
Frederic Riss1036e642015-02-13 23:18:22 +00002611 // Look for relocations that correspond to debug map entries.
2612 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002613 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002614 outs() << "No valid relocations found. Skipping.\n";
2615 continue;
2616 }
2617
Frederic Riss563cba62015-01-28 22:15:14 +00002618 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002619 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002620 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002621
Frederic Riss563cba62015-01-28 22:15:14 +00002622 // In a first phase, just read in the debug info and store the DIE
2623 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002624 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002625 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002626 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002627 outs() << "Input compilation unit:";
2628 CUDie->dump(outs(), CU.get(), 0);
2629 }
Frederic Riss3cced052015-03-14 03:46:40 +00002630 Units.emplace_back(*CU, UnitID++);
Frederic Riss9aa725b2015-02-13 23:18:31 +00002631 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00002632 }
Frederic Riss563cba62015-01-28 22:15:14 +00002633
Frederic Riss84c09a52015-02-13 23:18:34 +00002634 // Then mark all the DIEs that need to be present in the linked
2635 // output and collect some information about them. Note that this
2636 // loop can not be merged with the previous one becaue cross-cu
2637 // references require the ParentIdx to be setup for every CU in
2638 // the object file before calling this.
2639 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002640 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00002641 CurrentUnit, 0);
2642
Frederic Riss23e20e92015-03-07 01:25:09 +00002643 // The calls to applyValidRelocs inside cloneDIE will walk the
2644 // reloc array again (in the same way findValidRelocsInDebugInfo()
2645 // did). We need to reset the NextValidReloc index to the beginning.
2646 NextValidReloc = 0;
2647
Frederic Rissb8b43d52015-03-04 22:07:44 +00002648 // Construct the output DIE tree by cloning the DIEs we chose to
2649 // keep above. If there are no valid relocs, then there's nothing
2650 // to clone/emit.
2651 if (!ValidRelocs.empty())
2652 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002653 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00002654 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00002655 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2656 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002657 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00002658 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00002659 if (Options.NoOutput)
2660 continue;
2661 // FIXME: for compatibility with the classic dsymutil, we emit
2662 // an empty line table for the unit, even if the unit doesn't
2663 // actually exist in the DIE tree.
2664 patchLineTableForUnit(CurrentUnit, DwarfContext);
2665 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00002666 continue;
2667 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00002668 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002669 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002670 }
2671
2672 // Emit all the compile unit's debug information.
2673 if (!ValidRelocs.empty() && !Options.NoOutput)
2674 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00002675 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00002676 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002677 Streamer->emitCompileUnitHeader(CurrentUnit);
2678 if (!CurrentUnit.getOutputUnitDIE())
2679 continue;
2680 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2681 }
2682
Frederic Riss5a642072015-06-05 23:06:11 +00002683 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
2684 patchFrameInfoForObject(*Obj, DwarfContext,
2685 Units[0].getOrigUnit().getAddressByteSize());
2686
Frederic Riss563cba62015-01-28 22:15:14 +00002687 // Clean-up before starting working on the next object.
2688 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00002689 }
2690
Frederic Rissb8b43d52015-03-04 22:07:44 +00002691 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00002692 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002693 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00002694 Streamer->emitStrings(StringPool);
2695 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002696
Frederic Rissc99ea202015-02-28 00:29:11 +00002697 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00002698}
2699}
Frederic Rissd3455182015-01-28 18:27:01 +00002700
Frederic Rissb9818322015-02-28 00:29:07 +00002701bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2702 const LinkOptions &Options) {
2703 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00002704 return Linker.link(DM);
2705}
2706}
Frederic Riss231f7142014-12-12 17:31:24 +00002707}