blob: 31b7d118e4ec9c5c5580e8ee8af77bd22c48a9f4 [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"
25#include "llvm/MC/MCInstrInfo.h"
26#include "llvm/MC/MCObjectFileInfo.h"
27#include "llvm/MC/MCRegisterInfo.h"
28#include "llvm/MC/MCStreamer.h"
Frederic Riss1036e642015-02-13 23:18:22 +000029#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000030#include "llvm/Support/Dwarf.h"
31#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000032#include "llvm/Support/TargetRegistry.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000035#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000036#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000037
38namespace llvm {
39namespace dsymutil {
40
Frederic Rissd3455182015-01-28 18:27:01 +000041namespace {
42
Frederic Rissdef4fb72015-02-28 00:29:01 +000043void warn(const Twine &Warning, const Twine &Context) {
44 errs() << Twine("while processing ") + Context + ":\n";
45 errs() << Twine("warning: ") + Warning + "\n";
46}
47
Frederic Rissc99ea202015-02-28 00:29:11 +000048bool error(const Twine &Error, const Twine &Context) {
49 errs() << Twine("while processing ") + Context + ":\n";
50 errs() << Twine("error: ") + Error + "\n";
51 return false;
52}
53
Frederic Riss1af75f72015-03-12 18:45:10 +000054template <typename KeyT, typename ValT>
55using HalfOpenIntervalMap =
56 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
57 IntervalMapHalfOpenInfo<KeyT>>;
58
Frederic Riss25440872015-03-13 23:30:31 +000059typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
60
Frederic Riss563cba62015-01-28 22:15:14 +000061/// \brief Stores all information relating to a compile unit, be it in
62/// its original instance in the object file to its brand new cloned
63/// and linked DIE tree.
64class CompileUnit {
65public:
66 /// \brief Information gathered about a DIE in the object file.
67 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +000068 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss9833de62015-03-06 23:22:53 +000069 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +000070 uint32_t ParentIdx; ///< The index of this DIE's parent.
71 bool Keep; ///< Is the DIE part of the linked output?
72 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +000073 };
74
Frederic Riss3cced052015-03-14 03:46:40 +000075 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
76 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Frederic Riss25440872015-03-13 23:30:31 +000077 Ranges(RangeAlloc), UnitRangeAttribute(nullptr) {
Frederic Riss563cba62015-01-28 22:15:14 +000078 Info.resize(OrigUnit.getNumDIEs());
79 }
80
Frederic Riss2838f9e2015-03-05 05:29:05 +000081 CompileUnit(CompileUnit &&RHS)
82 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
83 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +000084 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
85 // The CompileUnit container has been 'reserve()'d with the right
86 // size. We cannot move the IntervalMap anyway.
87 llvm_unreachable("CompileUnits should not be moved.");
88 }
David Blaikiea8adc132015-03-04 22:20:52 +000089
Frederic Rissc3349d42015-02-13 23:18:27 +000090 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +000091
Frederic Riss3cced052015-03-14 03:46:40 +000092 unsigned getUniqueID() const { return ID; }
93
Frederic Rissb8b43d52015-03-04 22:07:44 +000094 DIE *getOutputUnitDIE() const { return CUDie.get(); }
95 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
96
Frederic Riss563cba62015-01-28 22:15:14 +000097 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
98 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
99
Frederic Rissb8b43d52015-03-04 22:07:44 +0000100 uint64_t getStartOffset() const { return StartOffset; }
101 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000102 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000103
Frederic Riss5a62dc32015-03-13 18:35:54 +0000104 uint64_t getLowPc() const { return LowPc; }
105 uint64_t getHighPc() const { return HighPc; }
106
Frederic Riss25440872015-03-13 23:30:31 +0000107 DIEInteger *getUnitRangesAttribute() const { return UnitRangeAttribute; }
108 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
109 const std::vector<DIEInteger *> &getRangesAttributes() const {
110 return RangeAttributes;
111 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000112
Frederic Rissdfb97902015-03-14 15:49:07 +0000113 const std::vector<std::pair<DIEInteger *, int64_t>> &
114 getLocationAttributes() const {
115 return LocationAttributes;
116 }
117
Frederic Riss9d441b62015-03-06 23:22:50 +0000118 /// \brief Compute the end offset for this unit. Must be
119 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000120 /// \returns the next unit offset (which is also the current
121 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000122 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000123
Frederic Riss6afcfce2015-03-13 18:35:57 +0000124 /// \brief Keep track of a forward reference to DIE \p Die in \p
125 /// RefUnit by \p Attr. The attribute should be fixed up later to
126 /// point to the absolute offset of \p Die in the debug_info section.
127 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
128 DIEInteger *Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000129
130 /// \brief Apply all fixups recored by noteForwardReference().
131 void fixupForwardReferences();
132
Frederic Riss1af75f72015-03-12 18:45:10 +0000133 /// \brief Add a function range [\p LowPC, \p HighPC) that is
134 /// relocatad by applying offset \p PCOffset.
135 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
136
Frederic Riss5c9c7062015-03-13 23:55:29 +0000137 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000138 /// patch up later.
139 void noteRangeAttribute(const DIE &Die, DIEInteger *Attr);
140
Frederic Rissdfb97902015-03-14 15:49:07 +0000141 /// \brief Keep track of a location attribute pointing to a location
142 /// list in the debug_loc section.
143 void noteLocationAttribute(DIEInteger *Attr, int64_t PcOffset);
144
Frederic Riss563cba62015-01-28 22:15:14 +0000145private:
146 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000147 unsigned ID;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000148 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
149 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
150
151 uint64_t StartOffset;
152 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000153
Frederic Riss5a62dc32015-03-13 18:35:54 +0000154 uint64_t LowPc;
155 uint64_t HighPc;
156
Frederic Riss9833de62015-03-06 23:22:53 +0000157 /// \brief A list of attributes to fixup with the absolute offset of
158 /// a DIE in the debug_info section.
159 ///
160 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000161 /// cloning because for cross-cu forward refences the target DIE's
162 /// offset isn't known you emit the reference attribute.
163 std::vector<std::tuple<DIE *, const CompileUnit *, DIEInteger *>>
164 ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000165
Frederic Riss25440872015-03-13 23:30:31 +0000166 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000167 /// \brief The ranges in that interval map are the PC ranges for
168 /// functions in this unit, associated with the PC offset to apply
169 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000170 FunctionIntervals Ranges;
171
172 /// \brief DW_AT_ranges attributes to patch after we have gathered
173 /// all the unit's function addresses.
174 /// @{
175 std::vector<DIEInteger *> RangeAttributes;
176 DIEInteger *UnitRangeAttribute;
177 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000178
179 /// \brief Location attributes that need to be transfered from th
180 /// original debug_loc section to the liked one. They are stored
181 /// along with the PC offset that is to be applied to their
182 /// function's address.
183 std::vector<std::pair<DIEInteger *, int64_t>> LocationAttributes;
Frederic Riss563cba62015-01-28 22:15:14 +0000184};
185
Frederic Riss9d441b62015-03-06 23:22:50 +0000186uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000187 NextUnitOffset = StartOffset + 11 /* Header size */;
188 // The root DIE might be null, meaning that the Unit had nothing to
189 // contribute to the linked output. In that case, we will emit the
190 // unit header without any actual DIE.
191 if (CUDie)
192 NextUnitOffset += CUDie->getSize();
193 return NextUnitOffset;
194}
195
Frederic Riss6afcfce2015-03-13 18:35:57 +0000196/// \brief Keep track of a forward cross-cu reference from this unit
197/// to \p Die that lives in \p RefUnit.
198void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
199 DIEInteger *Attr) {
200 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000201}
202
203/// \brief Apply all fixups recorded by noteForwardReference().
204void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000205 for (const auto &Ref : ForwardDIEReferences) {
206 DIE *RefDie;
207 const CompileUnit *RefUnit;
208 DIEInteger *Attr;
209 std::tie(RefDie, RefUnit, Attr) = Ref;
210 Attr->setValue(RefDie->getOffset() + RefUnit->getStartOffset());
211 }
Frederic Riss9833de62015-03-06 23:22:53 +0000212}
213
Frederic Riss5a62dc32015-03-13 18:35:54 +0000214void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
215 int64_t PcOffset) {
216 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
217 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
218 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000219}
220
Frederic Riss25440872015-03-13 23:30:31 +0000221void CompileUnit::noteRangeAttribute(const DIE &Die, DIEInteger *Attr) {
222 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
223 RangeAttributes.push_back(Attr);
224 else
225 UnitRangeAttribute = Attr;
226}
227
Frederic Rissdfb97902015-03-14 15:49:07 +0000228void CompileUnit::noteLocationAttribute(DIEInteger *Attr, int64_t PcOffset) {
229 LocationAttributes.emplace_back(Attr, PcOffset);
230}
231
Frederic Rissef648462015-03-06 17:56:30 +0000232/// \brief A string table that doesn't need relocations.
233///
234/// We are doing a final link, no need for a string table that
235/// has relocation entries for every reference to it. This class
236/// provides this ablitity by just associating offsets with
237/// strings.
238class NonRelocatableStringpool {
239public:
240 /// \brief Entries are stored into the StringMap and simply linked
241 /// together through the second element of this pair in order to
242 /// keep track of insertion order.
243 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
244 MapTy;
245
246 NonRelocatableStringpool()
247 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
248 // Legacy dsymutil puts an empty string at the start of the line
249 // table.
250 getStringOffset("");
251 }
252
253 /// \brief Get the offset of string \p S in the string table. This
254 /// can insert a new element or return the offset of a preexisitng
255 /// one.
256 uint32_t getStringOffset(StringRef S);
257
258 /// \brief Get permanent storage for \p S (but do not necessarily
259 /// emit \p S in the output section).
260 /// \returns The StringRef that points to permanent storage to use
261 /// in place of \p S.
262 StringRef internString(StringRef S);
263
264 // \brief Return the first entry of the string table.
265 const MapTy::MapEntryTy *getFirstEntry() const {
266 return getNextEntry(&Sentinel);
267 }
268
269 // \brief Get the entry following \p E in the string table or null
270 // if \p E was the last entry.
271 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
272 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
273 }
274
275 uint64_t getSize() { return CurrentEndOffset; }
276
277private:
278 MapTy Strings;
279 uint32_t CurrentEndOffset;
280 MapTy::MapEntryTy Sentinel, *Last;
281};
282
283/// \brief Get the offset of string \p S in the string table. This
284/// can insert a new element or return the offset of a preexisitng
285/// one.
286uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
287 if (S.empty() && !Strings.empty())
288 return 0;
289
290 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
291 MapTy::iterator It;
292 bool Inserted;
293
294 // A non-empty string can't be at offset 0, so if we have an entry
295 // with a 0 offset, it must be a previously interned string.
296 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
297 if (Inserted || It->getValue().first == 0) {
298 // Set offset and chain at the end of the entries list.
299 It->getValue().first = CurrentEndOffset;
300 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
301 Last->getValue().second = &*It;
302 Last = &*It;
303 }
304 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000305}
Frederic Rissef648462015-03-06 17:56:30 +0000306
307/// \brief Put \p S into the StringMap so that it gets permanent
308/// storage, but do not actually link it in the chain of elements
309/// that go into the output section. A latter call to
310/// getStringOffset() with the same string will chain it though.
311StringRef NonRelocatableStringpool::internString(StringRef S) {
312 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
313 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
314 return InsertResult.first->getKey();
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000315}
Frederic Rissef648462015-03-06 17:56:30 +0000316
Frederic Rissc99ea202015-02-28 00:29:11 +0000317/// \brief The Dwarf streaming logic
318///
319/// All interactions with the MC layer that is used to build the debug
320/// information binary representation are handled in this class.
321class DwarfStreamer {
322 /// \defgroup MCObjects MC layer objects constructed by the streamer
323 /// @{
324 std::unique_ptr<MCRegisterInfo> MRI;
325 std::unique_ptr<MCAsmInfo> MAI;
326 std::unique_ptr<MCObjectFileInfo> MOFI;
327 std::unique_ptr<MCContext> MC;
328 MCAsmBackend *MAB; // Owned by MCStreamer
329 std::unique_ptr<MCInstrInfo> MII;
330 std::unique_ptr<MCSubtargetInfo> MSTI;
331 MCCodeEmitter *MCE; // Owned by MCStreamer
332 MCStreamer *MS; // Owned by AsmPrinter
333 std::unique_ptr<TargetMachine> TM;
334 std::unique_ptr<AsmPrinter> Asm;
335 /// @}
336
337 /// \brief the file we stream the linked Dwarf to.
338 std::unique_ptr<raw_fd_ostream> OutFile;
339
Frederic Riss25440872015-03-13 23:30:31 +0000340 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000341 uint32_t LocSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000342
Frederic Rissc99ea202015-02-28 00:29:11 +0000343public:
344 /// \brief Actually create the streamer and the ouptut file.
345 ///
346 /// This could be done directly in the constructor, but it feels
347 /// more natural to handle errors through return value.
348 bool init(Triple TheTriple, StringRef OutputFilename);
349
Frederic Rissb8b43d52015-03-04 22:07:44 +0000350 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000351 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000352
353 AsmPrinter &getAsmPrinter() const { return *Asm; }
354
355 /// \brief Set the current output section to debug_info and change
356 /// the MC Dwarf version to \p DwarfVersion.
357 void switchToDebugInfoSection(unsigned DwarfVersion);
358
359 /// \brief Emit the compilation unit header for \p Unit in the
360 /// debug_info section.
361 ///
362 /// As a side effect, this also switches the current Dwarf version
363 /// of the MC layer to the one of U.getOrigUnit().
364 void emitCompileUnitHeader(CompileUnit &Unit);
365
366 /// \brief Recursively emit the DIE tree rooted at \p Die.
367 void emitDIE(DIE &Die);
368
369 /// \brief Emit the abbreviation table \p Abbrevs to the
370 /// debug_abbrev section.
371 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000372
373 /// \brief Emit the string table described by \p Pool.
374 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000375
376 /// \brief Emit debug_ranges for \p FuncRange by translating the
377 /// original \p Entries.
378 void emitRangesEntries(
379 int64_t UnitPcOffset, uint64_t OrigLowPc,
380 FunctionIntervals::const_iterator FuncRange,
381 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
382 unsigned AddressSize);
383
Frederic Riss563b1b02015-03-14 03:46:51 +0000384 /// \brief Emit debug_aranges entries for \p Unit and if \p
385 /// DoRangesSection is true, also emit the debug_ranges entries for
386 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
387 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000388
389 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000390
391 /// \brief Emit the debug_loc contribution for \p Unit by copying
392 /// the entries from \p Dwarf and offseting them. Update the
393 /// location attributes to point to the new entries.
394 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Rissc99ea202015-02-28 00:29:11 +0000395};
396
397bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
398 std::string ErrorStr;
399 std::string TripleName;
400 StringRef Context = "dwarf streamer init";
401
402 // Get the target.
403 const Target *TheTarget =
404 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
405 if (!TheTarget)
406 return error(ErrorStr, Context);
407 TripleName = TheTriple.getTriple();
408
409 // Create all the MC Objects.
410 MRI.reset(TheTarget->createMCRegInfo(TripleName));
411 if (!MRI)
412 return error(Twine("no register info for target ") + TripleName, Context);
413
414 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
415 if (!MAI)
416 return error("no asm info for target " + TripleName, Context);
417
418 MOFI.reset(new MCObjectFileInfo);
419 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
420 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
421 *MC);
422
423 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
424 if (!MAB)
425 return error("no asm backend for target " + TripleName, Context);
426
427 MII.reset(TheTarget->createMCInstrInfo());
428 if (!MII)
429 return error("no instr info info for target " + TripleName, Context);
430
431 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
432 if (!MSTI)
433 return error("no subtarget info for target " + TripleName, Context);
434
Eric Christopher0169e422015-03-10 22:03:14 +0000435 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000436 if (!MCE)
437 return error("no code emitter for target " + TripleName, Context);
438
439 // Create the output file.
440 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000441 OutFile =
442 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000443 if (EC)
444 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
445
446 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
447 *MSTI, false);
448 if (!MS)
449 return error("no object streamer for target " + TripleName, Context);
450
451 // Finally create the AsmPrinter we'll use to emit the DIEs.
452 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
453 if (!TM)
454 return error("no target machine for target " + TripleName, Context);
455
456 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
457 if (!Asm)
458 return error("no asm printer for target " + TripleName, Context);
459
Frederic Riss25440872015-03-13 23:30:31 +0000460 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000461 LocSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000462
Frederic Rissc99ea202015-02-28 00:29:11 +0000463 return true;
464}
465
466bool DwarfStreamer::finish() {
467 MS->Finish();
468 return true;
469}
470
Frederic Rissb8b43d52015-03-04 22:07:44 +0000471/// \brief Set the current output section to debug_info and change
472/// the MC Dwarf version to \p DwarfVersion.
473void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
474 MS->SwitchSection(MOFI->getDwarfInfoSection());
475 MC->setDwarfVersion(DwarfVersion);
476}
477
478/// \brief Emit the compilation unit header for \p Unit in the
479/// debug_info section.
480///
481/// A Dwarf scetion header is encoded as:
482/// uint32_t Unit length (omiting this field)
483/// uint16_t Version
484/// uint32_t Abbreviation table offset
485/// uint8_t Address size
486///
487/// Leading to a total of 11 bytes.
488void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
489 unsigned Version = Unit.getOrigUnit().getVersion();
490 switchToDebugInfoSection(Version);
491
492 // Emit size of content not including length itself. The size has
493 // already been computed in CompileUnit::computeOffsets(). Substract
494 // 4 to that size to account for the length field.
495 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
496 Asm->EmitInt16(Version);
497 // We share one abbreviations table across all units so it's always at the
498 // start of the section.
499 Asm->EmitInt32(0);
500 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
501}
502
503/// \brief Emit the \p Abbrevs array as the shared abbreviation table
504/// for the linked Dwarf file.
505void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
506 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
507 Asm->emitDwarfAbbrevs(Abbrevs);
508}
509
510/// \brief Recursively emit the DIE tree rooted at \p Die.
511void DwarfStreamer::emitDIE(DIE &Die) {
512 MS->SwitchSection(MOFI->getDwarfInfoSection());
513 Asm->emitDwarfDIE(Die);
514}
515
Frederic Rissef648462015-03-06 17:56:30 +0000516/// \brief Emit the debug_str section stored in \p Pool.
517void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
518 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
519 for (auto *Entry = Pool.getFirstEntry(); Entry;
520 Entry = Pool.getNextEntry(Entry))
521 Asm->OutStreamer.EmitBytes(
522 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
523}
524
Frederic Riss25440872015-03-13 23:30:31 +0000525/// \brief Emit the debug_range section contents for \p FuncRange by
526/// translating the original \p Entries. The debug_range section
527/// format is totally trivial, consisting just of pairs of address
528/// sized addresses describing the ranges.
529void DwarfStreamer::emitRangesEntries(
530 int64_t UnitPcOffset, uint64_t OrigLowPc,
531 FunctionIntervals::const_iterator FuncRange,
532 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
533 unsigned AddressSize) {
534 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
535
536 // Offset each range by the right amount.
537 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
538 for (const auto &Range : Entries) {
539 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
540 warn("unsupported base address selection operation",
541 "emitting debug_ranges");
542 break;
543 }
544 // Do not emit empty ranges.
545 if (Range.StartAddress == Range.EndAddress)
546 continue;
547
548 // All range entries should lie in the function range.
549 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
550 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
551 warn("inconsistent range data.", "emitting debug_ranges");
552 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
553 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
554 RangesSectionSize += 2 * AddressSize;
555 }
556
557 // Add the terminator entry.
558 MS->EmitIntValue(0, AddressSize);
559 MS->EmitIntValue(0, AddressSize);
560 RangesSectionSize += 2 * AddressSize;
561}
562
Frederic Riss563b1b02015-03-14 03:46:51 +0000563/// \brief Emit the debug_aranges contribution of a unit and
564/// if \p DoDebugRanges is true the debug_range contents for a
565/// compile_unit level DW_AT_ranges attribute (Which are basically the
566/// same thing with a different base address).
567/// Just aggregate all the ranges gathered inside that unit.
568void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
569 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000570 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
571 // Gather the ranges in a vector, so that we can simplify them. The
572 // IntervalMap will have coalesced the non-linked ranges, but here
573 // we want to coalesce the linked addresses.
574 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
575 const auto &FunctionRanges = Unit.getFunctionRanges();
576 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
577 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000578 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
579 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000580
581 // The object addresses where sorted, but again, the linked
582 // addresses might end up in a different order.
583 std::sort(Ranges.begin(), Ranges.end());
584
Frederic Riss563b1b02015-03-14 03:46:51 +0000585 if (!Ranges.empty()) {
586 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
587
588 MCSymbol *BeginLabel = Asm->GetTempSymbol("Barange", Unit.getUniqueID());
589 MCSymbol *EndLabel = Asm->GetTempSymbol("Earange", Unit.getUniqueID());
590
591 unsigned HeaderSize =
592 sizeof(int32_t) + // Size of contents (w/o this field
593 sizeof(int16_t) + // DWARF ARange version number
594 sizeof(int32_t) + // Offset of CU in the .debug_info section
595 sizeof(int8_t) + // Pointer Size (in bytes)
596 sizeof(int8_t); // Segment Size (in bytes)
597
598 unsigned TupleSize = AddressSize * 2;
599 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
600
601 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
602 Asm->OutStreamer.EmitLabel(BeginLabel);
603 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
604 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
605 Asm->EmitInt8(AddressSize); // Address size
606 Asm->EmitInt8(0); // Segment size
607
608 Asm->OutStreamer.EmitFill(Padding, 0x0);
609
610 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
611 ++Range) {
612 uint64_t RangeStart = Range->first;
613 MS->EmitIntValue(RangeStart, AddressSize);
614 while ((Range + 1) != End && Range->second == (Range + 1)->first)
615 ++Range;
616 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
617 }
618
619 // Emit terminator
620 Asm->OutStreamer.EmitIntValue(0, AddressSize);
621 Asm->OutStreamer.EmitIntValue(0, AddressSize);
622 Asm->OutStreamer.EmitLabel(EndLabel);
623 }
624
625 if (!DoDebugRanges)
626 return;
627
628 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
629 // Offset each range by the right amount.
630 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000631 // Emit coalesced ranges.
632 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000633 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000634 while (Range + 1 != End && Range->second == (Range + 1)->first)
635 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000636 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000637 RangesSectionSize += 2 * AddressSize;
638 }
639
640 // Add the terminator entry.
641 MS->EmitIntValue(0, AddressSize);
642 MS->EmitIntValue(0, AddressSize);
643 RangesSectionSize += 2 * AddressSize;
644}
645
Frederic Rissdfb97902015-03-14 15:49:07 +0000646/// \brief Emit location lists for \p Unit and update attribtues to
647/// point to the new entries.
648void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
649 DWARFContext &Dwarf) {
650 const std::vector<std::pair<DIEInteger *, int64_t>> &Attributes =
651 Unit.getLocationAttributes();
652
653 if (Attributes.empty())
654 return;
655
656 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
657
658 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
659 const DWARFSection &InputSec = Dwarf.getLocSection();
660 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
661 DWARFUnit &OrigUnit = Unit.getOrigUnit();
662 const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
663 int64_t UnitPcOffset = 0;
664 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
665 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
666 if (OrigLowPc != -1ULL)
667 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
668
669 for (const auto &Attr : Attributes) {
670 uint32_t Offset = Attr.first->getValue();
671 Attr.first->setValue(LocSectionSize);
672 // This is the quantity to add to the old location address to get
673 // the correct address for the new one.
674 int64_t LocPcOffset = Attr.second + UnitPcOffset;
675 while (Data.isValidOffset(Offset)) {
676 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
677 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
678 LocSectionSize += 2 * AddressSize;
679 if (Low == 0 && High == 0) {
680 Asm->OutStreamer.EmitIntValue(0, AddressSize);
681 Asm->OutStreamer.EmitIntValue(0, AddressSize);
682 break;
683 }
684 Asm->OutStreamer.EmitIntValue(Low + LocPcOffset, AddressSize);
685 Asm->OutStreamer.EmitIntValue(High + LocPcOffset, AddressSize);
686 uint64_t Length = Data.getU16(&Offset);
687 Asm->OutStreamer.EmitIntValue(Length, 2);
688 // Just copy the bytes over.
689 Asm->OutStreamer.EmitBytes(
690 StringRef(InputSec.Data.substr(Offset, Length)));
691 Offset += Length;
692 LocSectionSize += Length + 2;
693 }
694 }
695}
696
Frederic Rissd3455182015-01-28 18:27:01 +0000697/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000698///
699/// The link of the dwarf information from the object files will be
700/// driven by the selection of 'root DIEs', which are DIEs that
701/// describe variables or functions that are present in the linked
702/// binary (and thus have entries in the debug map). All the debug
703/// information that will be linked (the DIEs, but also the line
704/// tables, ranges, ...) is derived from that set of root DIEs.
705///
706/// The root DIEs are identified because they contain relocations that
707/// correspond to a debug map entry at specific places (the low_pc for
708/// a function, the location for a variable). These relocations are
709/// called ValidRelocs in the DwarfLinker and are gathered as a very
710/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +0000711class DwarfLinker {
712public:
Frederic Rissb9818322015-02-28 00:29:07 +0000713 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
714 : OutputFilename(OutputFilename), Options(Options),
715 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +0000716
Frederic Rissb8b43d52015-03-04 22:07:44 +0000717 ~DwarfLinker() {
718 for (auto *Abbrev : Abbreviations)
719 delete Abbrev;
720 }
721
Frederic Rissd3455182015-01-28 18:27:01 +0000722 /// \brief Link the contents of the DebugMap.
723 bool link(const DebugMap &);
724
725private:
Frederic Riss563cba62015-01-28 22:15:14 +0000726 /// \brief Called at the start of a debug object link.
727 void startDebugObject(DWARFContext &);
728
729 /// \brief Called at the end of a debug object link.
730 void endDebugObject();
731
Frederic Riss1036e642015-02-13 23:18:22 +0000732 /// \defgroup FindValidRelocations Translate debug map into a list
733 /// of relevant relocations
734 ///
735 /// @{
736 struct ValidReloc {
737 uint32_t Offset;
738 uint32_t Size;
739 uint64_t Addend;
740 const DebugMapObject::DebugMapEntry *Mapping;
741
742 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
743 const DebugMapObject::DebugMapEntry *Mapping)
744 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
745
746 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
747 };
748
749 /// \brief The valid relocations for the current DebugMapObject.
750 /// This vector is sorted by relocation offset.
751 std::vector<ValidReloc> ValidRelocs;
752
753 /// \brief Index into ValidRelocs of the next relocation to
754 /// consider. As we walk the DIEs in acsending file offset and as
755 /// ValidRelocs is sorted by file offset, keeping this index
756 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +0000757 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +0000758 unsigned NextValidReloc;
759
760 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
761 const DebugMapObject &DMO);
762
763 bool findValidRelocs(const object::SectionRef &Section,
764 const object::ObjectFile &Obj,
765 const DebugMapObject &DMO);
766
767 void findValidRelocsMachO(const object::SectionRef &Section,
768 const object::MachOObjectFile &Obj,
769 const DebugMapObject &DMO);
770 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +0000771
Frederic Riss84c09a52015-02-13 23:18:34 +0000772 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
773 ///
774 /// @{
775 /// \brief Recursively walk the \p DIE tree and look for DIEs to
776 /// keep. Store that information in \p CU's DIEInfo.
777 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
778 const DebugMapObject &DMO, CompileUnit &CU,
779 unsigned Flags);
780
781 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
782 enum TravesalFlags {
783 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
784 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
785 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
786 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
787 };
788
789 /// \brief Mark the passed DIE as well as all the ones it depends on
790 /// as kept.
791 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
792 CompileUnit::DIEInfo &MyInfo,
793 const DebugMapObject &DMO, CompileUnit &CU,
794 unsigned Flags);
795
796 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
797 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
798 unsigned Flags);
799
800 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
801 CompileUnit &Unit,
802 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
803
804 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
805 CompileUnit &Unit,
806 CompileUnit::DIEInfo &MyInfo,
807 unsigned Flags);
808
809 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
810 CompileUnit::DIEInfo &Info);
811 /// @}
812
Frederic Rissb8b43d52015-03-04 22:07:44 +0000813 /// \defgroup Linking Methods used to link the debug information
814 ///
815 /// @{
816 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
817 /// where useless (as decided by lookForDIEsToKeep()) bits have been
818 /// stripped out and addresses have been rewritten according to the
819 /// debug map.
820 ///
821 /// \param OutOffset is the offset the cloned DIE in the output
822 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +0000823 /// \param PCOffset (while cloning a function scope) is the offset
824 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000825 ///
826 /// \returns the root of the cloned tree.
827 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +0000828 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000829
830 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
831
Frederic Riss31da3242015-03-11 18:45:52 +0000832 /// \brief Information gathered and exchanged between the various
833 /// clone*Attributes helpers about the attributes of a particular DIE.
834 struct AttributesInfo {
835 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
836 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
837
838 AttributesInfo() : OrigHighPc(0), PCOffset(0) {}
839 };
840
Frederic Rissb8b43d52015-03-04 22:07:44 +0000841 /// \brief Helper for cloneDIE.
842 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
843 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +0000844 const AttributeSpec AttrSpec, unsigned AttrSize,
845 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000846
847 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +0000848 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
849 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000850
851 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +0000852 unsigned
853 cloneDieReferenceAttribute(DIE &Die,
854 const DWARFDebugInfoEntryMinimal &InputDIE,
855 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +0000856 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000857
858 /// \brief Helper for cloneDIE.
859 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
860 const DWARFFormValue &Val, unsigned AttrSize);
861
862 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +0000863 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
864 const DWARFFormValue &Val,
865 const CompileUnit &Unit, AttributesInfo &Info);
866
867 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000868 unsigned cloneScalarAttribute(DIE &Die,
869 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +0000870 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +0000871 const DWARFFormValue &Val, unsigned AttrSize,
872 const AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000873
Frederic Riss23e20e92015-03-07 01:25:09 +0000874 /// \brief Helper for cloneDIE.
875 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
876 bool isLittleEndian);
877
Frederic Rissb8b43d52015-03-04 22:07:44 +0000878 /// \brief Assign an abbreviation number to \p Abbrev
879 void AssignAbbrev(DIEAbbrev &Abbrev);
880
881 /// \brief FoldingSet that uniques the abbreviations.
882 FoldingSet<DIEAbbrev> AbbreviationsSet;
883 /// \brief Storage for the unique Abbreviations.
884 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
885 /// be changed to a vecot of unique_ptrs.
886 std::vector<DIEAbbrev *> Abbreviations;
887
Frederic Riss25440872015-03-13 23:30:31 +0000888 /// \brief Compute and emit debug_ranges section for \p Unit, and
889 /// patch the attributes referencing it.
890 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
891
892 /// \brief Generate and emit the DW_AT_ranges attribute for a
893 /// compile_unit if it had one.
894 void generateUnitRanges(CompileUnit &Unit) const;
895
Frederic Rissb8b43d52015-03-04 22:07:44 +0000896 /// \brief DIELoc objects that need to be destructed (but not freed!).
897 std::vector<DIELoc *> DIELocs;
898 /// \brief DIEBlock objects that need to be destructed (but not freed!).
899 std::vector<DIEBlock *> DIEBlocks;
900 /// \brief Allocator used for all the DIEValue objects.
901 BumpPtrAllocator DIEAlloc;
902 /// @}
903
Frederic Riss1b9da422015-02-13 23:18:29 +0000904 /// \defgroup Helpers Various helper methods.
905 ///
906 /// @{
907 const DWARFDebugInfoEntryMinimal *
908 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
909 const DWARFDebugInfoEntryMinimal &DIE,
910 CompileUnit *&ReferencedCU);
911
912 CompileUnit *getUnitForOffset(unsigned Offset);
913
914 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +0000915 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +0000916
917 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +0000918 /// @}
919
Frederic Riss563cba62015-01-28 22:15:14 +0000920private:
Frederic Rissd3455182015-01-28 18:27:01 +0000921 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +0000922 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +0000923 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +0000924 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +0000925
926 /// The units of the current debug map object.
927 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +0000928
929 /// The debug map object curently under consideration.
930 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +0000931
932 /// \brief The Dwarf string pool
933 NonRelocatableStringpool StringPool;
Frederic Rissd3455182015-01-28 18:27:01 +0000934};
935
Frederic Riss1b9da422015-02-13 23:18:29 +0000936/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
937/// returning our CompileUnit object instead.
938CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
939 auto CU =
940 std::upper_bound(Units.begin(), Units.end(), Offset,
941 [](uint32_t LHS, const CompileUnit &RHS) {
942 return LHS < RHS.getOrigUnit().getNextUnitOffset();
943 });
944 return CU != Units.end() ? &*CU : nullptr;
945}
946
947/// \brief Resolve the DIE attribute reference that has been
948/// extracted in \p RefValue. The resulting DIE migh be in another
949/// CompileUnit which is stored into \p ReferencedCU.
950/// \returns null if resolving fails for any reason.
951const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
952 DWARFFormValue &RefValue, const DWARFUnit &Unit,
953 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
954 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
955 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
956
957 if ((RefCU = getUnitForOffset(RefOffset)))
958 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
959 return RefDie;
960
961 reportWarning("could not find referenced DIE", &Unit, &DIE);
962 return nullptr;
963}
964
965/// \brief Report a warning to the user, optionaly including
966/// information about a specific \p DIE related to the warning.
967void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +0000968 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +0000969 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +0000970 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +0000971 Context = CurrentDebugObject->getObjectFilename();
972 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +0000973
Frederic Rissb9818322015-02-28 00:29:07 +0000974 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +0000975 return;
976
977 errs() << " in DIE:\n";
978 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
979 6 /* Indent */);
980}
981
Frederic Rissc99ea202015-02-28 00:29:11 +0000982bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
983 if (Options.NoOutput)
984 return true;
985
Frederic Rissb52cf522015-02-28 00:42:37 +0000986 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +0000987 return Streamer->init(TheTriple, OutputFilename);
988}
989
Frederic Riss563cba62015-01-28 22:15:14 +0000990/// \brief Recursive helper to gather the child->parent relationships in the
991/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +0000992static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
993 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +0000994 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
995 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
996
997 if (DIE->hasChildren())
998 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
999 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +00001000 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +00001001}
1002
Frederic Riss84c09a52015-02-13 23:18:34 +00001003static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1004 switch (Tag) {
1005 default:
1006 return false;
1007 case dwarf::DW_TAG_subprogram:
1008 case dwarf::DW_TAG_lexical_block:
1009 case dwarf::DW_TAG_subroutine_type:
1010 case dwarf::DW_TAG_structure_type:
1011 case dwarf::DW_TAG_class_type:
1012 case dwarf::DW_TAG_union_type:
1013 return true;
1014 }
1015 llvm_unreachable("Invalid Tag");
1016}
1017
Frederic Riss563cba62015-01-28 22:15:14 +00001018void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
1019 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001020 NextValidReloc = 0;
Frederic Riss563cba62015-01-28 22:15:14 +00001021}
1022
Frederic Riss1036e642015-02-13 23:18:22 +00001023void DwarfLinker::endDebugObject() {
1024 Units.clear();
1025 ValidRelocs.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001026
1027 for (auto *Block : DIEBlocks)
1028 Block->~DIEBlock();
1029 for (auto *Loc : DIELocs)
1030 Loc->~DIELoc();
1031
1032 DIEBlocks.clear();
1033 DIELocs.clear();
1034 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001035}
1036
1037/// \brief Iterate over the relocations of the given \p Section and
1038/// store the ones that correspond to debug map entries into the
1039/// ValidRelocs array.
1040void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1041 const object::MachOObjectFile &Obj,
1042 const DebugMapObject &DMO) {
1043 StringRef Contents;
1044 Section.getContents(Contents);
1045 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1046
1047 for (const object::RelocationRef &Reloc : Section.relocations()) {
1048 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1049 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1050 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1051 uint64_t Offset64;
1052 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001053 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001054 continue;
1055 }
1056 uint32_t Offset = Offset64;
1057 // Mach-o uses REL relocations, the addend is at the relocation offset.
1058 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1059
1060 auto Sym = Reloc.getSymbol();
1061 if (Sym != Obj.symbol_end()) {
1062 StringRef SymbolName;
1063 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001064 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001065 continue;
1066 }
1067 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1068 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1069 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1070 // Do not store the addend. The addend was the address of the
1071 // symbol in the object file, the address in the binary that is
1072 // stored in the debug map doesn't need to be offseted.
1073 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1074 }
1075 }
1076}
1077
1078/// \brief Dispatch the valid relocation finding logic to the
1079/// appropriate handler depending on the object file format.
1080bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1081 const object::ObjectFile &Obj,
1082 const DebugMapObject &DMO) {
1083 // Dispatch to the right handler depending on the file type.
1084 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1085 findValidRelocsMachO(Section, *MachOObj, DMO);
1086 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001087 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001088
1089 if (ValidRelocs.empty())
1090 return false;
1091
1092 // Sort the relocations by offset. We will walk the DIEs linearly in
1093 // the file, this allows us to just keep an index in the relocation
1094 // array that we advance during our walk, rather than resorting to
1095 // some associative container. See DwarfLinker::NextValidReloc.
1096 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1097 return true;
1098}
1099
1100/// \brief Look for relocations in the debug_info section that match
1101/// entries in the debug map. These relocations will drive the Dwarf
1102/// link by indicating which DIEs refer to symbols present in the
1103/// linked binary.
1104/// \returns wether there are any valid relocations in the debug info.
1105bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1106 const DebugMapObject &DMO) {
1107 // Find the debug_info section.
1108 for (const object::SectionRef &Section : Obj.sections()) {
1109 StringRef SectionName;
1110 Section.getName(SectionName);
1111 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1112 if (SectionName != "debug_info")
1113 continue;
1114 return findValidRelocs(Section, Obj, DMO);
1115 }
1116 return false;
1117}
Frederic Riss563cba62015-01-28 22:15:14 +00001118
Frederic Riss84c09a52015-02-13 23:18:34 +00001119/// \brief Checks that there is a relocation against an actual debug
1120/// map entry between \p StartOffset and \p NextOffset.
1121///
1122/// This function must be called with offsets in strictly ascending
1123/// order because it never looks back at relocations it already 'went past'.
1124/// \returns true and sets Info.InDebugMap if it is the case.
1125bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1126 CompileUnit::DIEInfo &Info) {
1127 assert(NextValidReloc == 0 ||
1128 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1129 if (NextValidReloc >= ValidRelocs.size())
1130 return false;
1131
1132 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1133
1134 // We might need to skip some relocs that we didn't consider. For
1135 // example the high_pc of a discarded DIE might contain a reloc that
1136 // is in the list because it actually corresponds to the start of a
1137 // function that is in the debug map.
1138 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1139 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1140
1141 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1142 return false;
1143
1144 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +00001145 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001146 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1147 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1148 ValidReloc.Mapping->getValue().ObjectAddress,
1149 ValidReloc.Mapping->getValue().BinaryAddress);
1150
Frederic Riss31da3242015-03-11 18:45:52 +00001151 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1152 ValidReloc.Addend -
1153 ValidReloc.Mapping->getValue().ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001154 Info.InDebugMap = true;
1155 return true;
1156}
1157
1158/// \brief Get the starting and ending (exclusive) offset for the
1159/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1160/// supposed to point to the position of the first attribute described
1161/// by \p Abbrev.
1162/// \return [StartOffset, EndOffset) as a pair.
1163static std::pair<uint32_t, uint32_t>
1164getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1165 unsigned Offset, const DWARFUnit &Unit) {
1166 DataExtractor Data = Unit.getDebugInfoExtractor();
1167
1168 for (unsigned i = 0; i < Idx; ++i)
1169 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1170
1171 uint32_t End = Offset;
1172 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1173
1174 return std::make_pair(Offset, End);
1175}
1176
1177/// \brief Check if a variable describing DIE should be kept.
1178/// \returns updated TraversalFlags.
1179unsigned DwarfLinker::shouldKeepVariableDIE(
1180 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1181 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1182 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1183
1184 // Global variables with constant value can always be kept.
1185 if (!(Flags & TF_InFunctionScope) &&
1186 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1187 MyInfo.InDebugMap = true;
1188 return Flags | TF_Keep;
1189 }
1190
1191 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1192 if (LocationIdx == -1U)
1193 return Flags;
1194
1195 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1196 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1197 uint32_t LocationOffset, LocationEndOffset;
1198 std::tie(LocationOffset, LocationEndOffset) =
1199 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1200
1201 // See if there is a relocation to a valid debug map entry inside
1202 // this variable's location. The order is important here. We want to
1203 // always check in the variable has a valid relocation, so that the
1204 // DIEInfo is filled. However, we don't want a static variable in a
1205 // function to force us to keep the enclosing function.
1206 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1207 (Flags & TF_InFunctionScope))
1208 return Flags;
1209
Frederic Rissb9818322015-02-28 00:29:07 +00001210 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001211 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1212
1213 return Flags | TF_Keep;
1214}
1215
1216/// \brief Check if a function describing DIE should be kept.
1217/// \returns updated TraversalFlags.
1218unsigned DwarfLinker::shouldKeepSubprogramDIE(
1219 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1220 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1221 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1222
1223 Flags |= TF_InFunctionScope;
1224
1225 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1226 if (LowPcIdx == -1U)
1227 return Flags;
1228
1229 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1230 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1231 uint32_t LowPcOffset, LowPcEndOffset;
1232 std::tie(LowPcOffset, LowPcEndOffset) =
1233 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1234
1235 uint64_t LowPc =
1236 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1237 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1238 if (LowPc == -1ULL ||
1239 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1240 return Flags;
1241
Frederic Rissb9818322015-02-28 00:29:07 +00001242 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001243 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1244
Frederic Riss1af75f72015-03-12 18:45:10 +00001245 Flags |= TF_Keep;
1246
1247 DWARFFormValue HighPcValue;
1248 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1249 reportWarning("Function without high_pc. Range will be discarded.\n",
1250 &OrigUnit, &DIE);
1251 return Flags;
1252 }
1253
1254 uint64_t HighPc;
1255 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1256 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1257 } else {
1258 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1259 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1260 }
1261
1262 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1263 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001264}
1265
1266/// \brief Check if a DIE should be kept.
1267/// \returns updated TraversalFlags.
1268unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1269 CompileUnit &Unit,
1270 CompileUnit::DIEInfo &MyInfo,
1271 unsigned Flags) {
1272 switch (DIE.getTag()) {
1273 case dwarf::DW_TAG_constant:
1274 case dwarf::DW_TAG_variable:
1275 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1276 case dwarf::DW_TAG_subprogram:
1277 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1278 case dwarf::DW_TAG_module:
1279 case dwarf::DW_TAG_imported_module:
1280 case dwarf::DW_TAG_imported_declaration:
1281 case dwarf::DW_TAG_imported_unit:
1282 // We always want to keep these.
1283 return Flags | TF_Keep;
1284 }
1285
1286 return Flags;
1287}
1288
Frederic Riss84c09a52015-02-13 23:18:34 +00001289/// \brief Mark the passed DIE as well as all the ones it depends on
1290/// as kept.
1291///
1292/// This function is called by lookForDIEsToKeep on DIEs that are
1293/// newly discovered to be needed in the link. It recursively calls
1294/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1295/// TraversalFlags to inform it that it's not doing the primary DIE
1296/// tree walk.
1297void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1298 CompileUnit::DIEInfo &MyInfo,
1299 const DebugMapObject &DMO,
1300 CompileUnit &CU, unsigned Flags) {
1301 const DWARFUnit &Unit = CU.getOrigUnit();
1302 MyInfo.Keep = true;
1303
1304 // First mark all the parent chain as kept.
1305 unsigned AncestorIdx = MyInfo.ParentIdx;
1306 while (!CU.getInfo(AncestorIdx).Keep) {
1307 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1308 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1309 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1310 }
1311
1312 // Then we need to mark all the DIEs referenced by this DIE's
1313 // attributes as kept.
1314 DataExtractor Data = Unit.getDebugInfoExtractor();
1315 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1316 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1317
1318 // Mark all DIEs referenced through atttributes as kept.
1319 for (const auto &AttrSpec : Abbrev->attributes()) {
1320 DWARFFormValue Val(AttrSpec.Form);
1321
1322 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1323 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1324 continue;
1325 }
1326
1327 Val.extractValue(Data, &Offset, &Unit);
1328 CompileUnit *ReferencedCU;
1329 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1330 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1331 TF_Keep | TF_DependencyWalk);
1332 }
1333}
1334
1335/// \brief Recursively walk the \p DIE tree and look for DIEs to
1336/// keep. Store that information in \p CU's DIEInfo.
1337///
1338/// This function is the entry point of the DIE selection
1339/// algorithm. It is expected to walk the DIE tree in file order and
1340/// (though the mediation of its helper) call hasValidRelocation() on
1341/// each DIE that might be a 'root DIE' (See DwarfLinker class
1342/// comment).
1343/// While walking the dependencies of root DIEs, this function is
1344/// also called, but during these dependency walks the file order is
1345/// not respected. The TF_DependencyWalk flag tells us which kind of
1346/// traversal we are currently doing.
1347void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1348 const DebugMapObject &DMO, CompileUnit &CU,
1349 unsigned Flags) {
1350 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1351 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1352 bool AlreadyKept = MyInfo.Keep;
1353
1354 // If the Keep flag is set, we are marking a required DIE's
1355 // dependencies. If our target is already marked as kept, we're all
1356 // set.
1357 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1358 return;
1359
1360 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1361 // because it would screw up the relocation finding logic.
1362 if (!(Flags & TF_DependencyWalk))
1363 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1364
1365 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1366 if (!AlreadyKept && (Flags & TF_Keep))
1367 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1368
1369 // The TF_ParentWalk flag tells us that we are currently walking up
1370 // the parent chain of a required DIE, and we don't want to mark all
1371 // the children of the parents as kept (consider for example a
1372 // DW_TAG_namespace node in the parent chain). There are however a
1373 // set of DIE types for which we want to ignore that directive and still
1374 // walk their children.
1375 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1376 Flags &= ~TF_ParentWalk;
1377
1378 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1379 return;
1380
1381 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1382 Child = Child->getSibling())
1383 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1384}
1385
Frederic Rissb8b43d52015-03-04 22:07:44 +00001386/// \brief Assign an abbreviation numer to \p Abbrev.
1387///
1388/// Our DIEs get freed after every DebugMapObject has been processed,
1389/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1390/// the instances hold by the DIEs. When we encounter an abbreviation
1391/// that we don't know, we create a permanent copy of it.
1392void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1393 // Check the set for priors.
1394 FoldingSetNodeID ID;
1395 Abbrev.Profile(ID);
1396 void *InsertToken;
1397 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1398
1399 // If it's newly added.
1400 if (InSet) {
1401 // Assign existing abbreviation number.
1402 Abbrev.setNumber(InSet->getNumber());
1403 } else {
1404 // Add to abbreviation list.
1405 Abbreviations.push_back(
1406 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1407 for (const auto &Attr : Abbrev.getData())
1408 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1409 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1410 // Assign the unique abbreviation number.
1411 Abbrev.setNumber(Abbreviations.size());
1412 Abbreviations.back()->setNumber(Abbreviations.size());
1413 }
1414}
1415
1416/// \brief Clone a string attribute described by \p AttrSpec and add
1417/// it to \p Die.
1418/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001419unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1420 const DWARFFormValue &Val,
1421 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001422 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001423 const char *String = *Val.getAsCString(&U);
1424 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001425 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Frederic Rissef648462015-03-06 17:56:30 +00001426 new (DIEAlloc) DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001427 return 4;
1428}
1429
1430/// \brief Clone an attribute referencing another DIE and add
1431/// it to \p Die.
1432/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001433unsigned DwarfLinker::cloneDieReferenceAttribute(
1434 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1435 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001436 CompileUnit &Unit) {
1437 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
Frederic Riss9833de62015-03-06 23:22:53 +00001438 DIE *NewRefDie = nullptr;
1439 CompileUnit *RefUnit = nullptr;
1440 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1441
1442 if (!(RefUnit = getUnitForOffset(Ref)) ||
1443 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1444 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1445 if (!AttributeString)
1446 AttributeString = "DW_AT_???";
1447 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1448 ". Dropping.",
Frederic Riss6afcfce2015-03-13 18:35:57 +00001449 &Unit.getOrigUnit(), &InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001450 return 0;
1451 }
1452
1453 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1454 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1455 if (!RefInfo.Clone) {
1456 assert(Ref > InputDIE.getOffset());
1457 // We haven't cloned this DIE yet. Just create an empty one and
1458 // store it. It'll get really cloned when we process it.
1459 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1460 }
1461 NewRefDie = RefInfo.Clone;
1462
1463 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1464 // We cannot currently rely on a DIEEntry to emit ref_addr
1465 // references, because the implementation calls back to DwarfDebug
1466 // to find the unit offset. (We don't have a DwarfDebug)
1467 // FIXME: we should be able to design DIEEntry reliance on
1468 // DwarfDebug away.
1469 DIEInteger *Attr;
1470 if (Ref < InputDIE.getOffset()) {
1471 // We must have already cloned that DIE.
1472 uint32_t NewRefOffset =
1473 RefUnit->getStartOffset() + NewRefDie->getOffset();
1474 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1475 } else {
1476 // A forward reference. Note and fixup later.
1477 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
Frederic Riss6afcfce2015-03-13 18:35:57 +00001478 Unit.noteForwardReference(NewRefDie, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +00001479 }
1480 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1481 Attr);
1482 return AttrSize;
1483 }
1484
Frederic Rissb8b43d52015-03-04 22:07:44 +00001485 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss9833de62015-03-06 23:22:53 +00001486 new (DIEAlloc) DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001487 return AttrSize;
1488}
1489
1490/// \brief Clone an attribute of block form (locations, constants) and add
1491/// it to \p Die.
1492/// \returns the size of the new attribute.
1493unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1494 const DWARFFormValue &Val,
1495 unsigned AttrSize) {
1496 DIE *Attr;
1497 DIEValue *Value;
1498 DIELoc *Loc = nullptr;
1499 DIEBlock *Block = nullptr;
1500 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001501 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001502 Loc = new (DIEAlloc) DIELoc();
1503 DIELocs.push_back(Loc);
1504 } else {
1505 Block = new (DIEAlloc) DIEBlock();
1506 DIEBlocks.push_back(Block);
1507 }
1508 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1509 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1510 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1511 for (auto Byte : Bytes)
1512 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1513 new (DIEAlloc) DIEInteger(Byte));
1514 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1515 // the DIE class, this if could be replaced by
1516 // Attr->setSize(Bytes.size()).
1517 if (Streamer) {
1518 if (Loc)
1519 Loc->ComputeSize(&Streamer->getAsmPrinter());
1520 else
1521 Block->ComputeSize(&Streamer->getAsmPrinter());
1522 }
1523 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1524 Value);
1525 return AttrSize;
1526}
1527
Frederic Riss31da3242015-03-11 18:45:52 +00001528/// \brief Clone an address attribute and add it to \p Die.
1529/// \returns the size of the new attribute.
1530unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1531 const DWARFFormValue &Val,
1532 const CompileUnit &Unit,
1533 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001534 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00001535 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1536 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1537 Die.getTag() == dwarf::DW_TAG_lexical_block)
1538 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001539 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1540 Addr = Unit.getLowPc();
1541 if (Addr == UINT64_MAX)
1542 return 0;
1543 }
Frederic Riss31da3242015-03-11 18:45:52 +00001544 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001545 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1546 if (uint64_t HighPc = Unit.getHighPc())
1547 Addr = HighPc;
1548 else
1549 return 0;
1550 } else
1551 // If we have a high_pc recorded for the input DIE, use
1552 // it. Otherwise (when no relocations where applied) just use the
1553 // one we just decoded.
1554 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00001555 }
1556
1557 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1558 static_cast<dwarf::Form>(AttrSpec.Form),
1559 new (DIEAlloc) DIEInteger(Addr));
1560 return Unit.getOrigUnit().getAddressByteSize();
1561}
1562
Frederic Rissb8b43d52015-03-04 22:07:44 +00001563/// \brief Clone a scalar attribute and add it to \p Die.
1564/// \returns the size of the new attribute.
1565unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00001566 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00001567 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
1568 const AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001569 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001570 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1571 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1572 if (Unit.getLowPc() == -1ULL)
1573 return 0;
1574 // Dwarf >= 4 high_pc is an size, not an address.
1575 Value = Unit.getHighPc() - Unit.getLowPc();
1576 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00001577 Value = *Val.getAsSectionOffset();
1578 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1579 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001580 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1581 Value = *OptionalValue;
1582 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001583 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1584 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001585 return 0;
1586 }
Frederic Riss25440872015-03-13 23:30:31 +00001587 DIEInteger *Attr = new (DIEAlloc) DIEInteger(Value);
1588 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
1589 Unit.noteRangeAttribute(Die, Attr);
Frederic Rissdfb97902015-03-14 15:49:07 +00001590 // A more generic way to check for location attributes would be
1591 // nice, but it's very unlikely that any other attribute needs a
1592 // location list.
1593 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1594 AttrSpec.Attr == dwarf::DW_AT_frame_base)
1595 Unit.noteLocationAttribute(Attr, Info.PCOffset);
1596
Frederic Rissb8b43d52015-03-04 22:07:44 +00001597 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss25440872015-03-13 23:30:31 +00001598 Attr);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001599 return AttrSize;
1600}
1601
1602/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1603/// value \p Val, and add it to \p Die.
1604/// \returns the size of the cloned attribute.
1605unsigned DwarfLinker::cloneAttribute(DIE &Die,
1606 const DWARFDebugInfoEntryMinimal &InputDIE,
1607 CompileUnit &Unit,
1608 const DWARFFormValue &Val,
1609 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00001610 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001611 const DWARFUnit &U = Unit.getOrigUnit();
1612
1613 switch (AttrSpec.Form) {
1614 case dwarf::DW_FORM_strp:
1615 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00001616 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001617 case dwarf::DW_FORM_ref_addr:
1618 case dwarf::DW_FORM_ref1:
1619 case dwarf::DW_FORM_ref2:
1620 case dwarf::DW_FORM_ref4:
1621 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00001622 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001623 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001624 case dwarf::DW_FORM_block:
1625 case dwarf::DW_FORM_block1:
1626 case dwarf::DW_FORM_block2:
1627 case dwarf::DW_FORM_block4:
1628 case dwarf::DW_FORM_exprloc:
1629 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1630 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00001631 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001632 case dwarf::DW_FORM_data1:
1633 case dwarf::DW_FORM_data2:
1634 case dwarf::DW_FORM_data4:
1635 case dwarf::DW_FORM_data8:
1636 case dwarf::DW_FORM_udata:
1637 case dwarf::DW_FORM_sdata:
1638 case dwarf::DW_FORM_sec_offset:
1639 case dwarf::DW_FORM_flag:
1640 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00001641 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
1642 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001643 default:
1644 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1645 &InputDIE);
1646 }
1647
1648 return 0;
1649}
1650
Frederic Riss23e20e92015-03-07 01:25:09 +00001651/// \brief Apply the valid relocations found by findValidRelocs() to
1652/// the buffer \p Data, taking into account that Data is at \p BaseOffset
1653/// in the debug_info section.
1654///
1655/// Like for findValidRelocs(), this function must be called with
1656/// monotonic \p BaseOffset values.
1657///
1658/// \returns wether any reloc has been applied.
1659bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1660 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00001661 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00001662 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1663 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00001664 if (NextValidReloc >= ValidRelocs.size())
1665 return false;
1666
1667 // Skip relocs that haven't been applied.
1668 while (NextValidReloc < ValidRelocs.size() &&
1669 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1670 ++NextValidReloc;
1671
1672 bool Applied = false;
1673 uint64_t EndOffset = BaseOffset + Data.size();
1674 while (NextValidReloc < ValidRelocs.size() &&
1675 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1676 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1677 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1678 assert(ValidReloc.Offset - BaseOffset < Data.size());
1679 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1680 char Buf[8];
1681 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1682 Value += ValidReloc.Addend;
1683 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1684 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1685 Buf[i] = uint8_t(Value >> (Index * 8));
1686 }
1687 assert(ValidReloc.Size <= sizeof(Buf));
1688 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1689 Applied = true;
1690 }
1691
1692 return Applied;
1693}
1694
Frederic Rissb8b43d52015-03-04 22:07:44 +00001695/// \brief Recursively clone \p InputDIE's subtrees that have been
1696/// selected to appear in the linked output.
1697///
1698/// \param OutOffset is the Offset where the newly created DIE will
1699/// lie in the linked compile unit.
1700///
1701/// \returns the cloned DIE object or null if nothing was selected.
1702DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00001703 CompileUnit &Unit, int64_t PCOffset,
1704 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001705 DWARFUnit &U = Unit.getOrigUnit();
1706 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001707 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001708
1709 // Should the DIE appear in the output?
1710 if (!Unit.getInfo(Idx).Keep)
1711 return nullptr;
1712
1713 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00001714 // The DIE might have been already created by a forward reference
1715 // (see cloneDieReferenceAttribute()).
1716 DIE *Die = Info.Clone;
1717 if (!Die)
1718 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1719 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00001720 Die->setOffset(OutOffset);
1721
1722 // Extract and clone every attribute.
1723 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00001724 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00001725 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00001726
1727 // We could copy the data only if we need to aply a relocation to
1728 // it. After testing, it seems there is no performance downside to
1729 // doing the copy unconditionally, and it makes the code simpler.
1730 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1731 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1732 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00001733 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1734 // If we applied relocations, we store the value of high_pc that was
1735 // potentially stored in the input DIE. If high_pc is an address
1736 // (Dwarf version == 2), then it might have been relocated to a
1737 // totally unrelated value (because the end address in the object
1738 // file might be start address of another function which got moved
1739 // independantly by the linker). The computation of the actual
1740 // high_pc value is done in cloneAddressAttribute().
1741 AttrInfo.OrigHighPc =
1742 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
1743 }
Frederic Riss23e20e92015-03-07 01:25:09 +00001744
1745 // Reset the Offset to 0 as we will be working on the local copy of
1746 // the data.
1747 Offset = 0;
1748
Frederic Rissb8b43d52015-03-04 22:07:44 +00001749 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1750 Offset += getULEB128Size(Abbrev->getCode());
1751
Frederic Riss31da3242015-03-11 18:45:52 +00001752 // We are entering a subprogram. Get and propagate the PCOffset.
1753 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1754 PCOffset = Info.AddrAdjust;
1755 AttrInfo.PCOffset = PCOffset;
1756
Frederic Rissb8b43d52015-03-04 22:07:44 +00001757 for (const auto &AttrSpec : Abbrev->attributes()) {
1758 DWARFFormValue Val(AttrSpec.Form);
1759 uint32_t AttrSize = Offset;
1760 Val.extractValue(Data, &Offset, &U);
1761 AttrSize = Offset - AttrSize;
1762
Frederic Riss31da3242015-03-11 18:45:52 +00001763 OutOffset +=
1764 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001765 }
1766
1767 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1768 // If a scope DIE is kept, we must have kept at least one child. If
1769 // it's not the case, we'll just be emitting one wasteful end of
1770 // children marker, but things won't break.
1771 if (InputDIE.hasChildren())
1772 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1773 // Assign a permanent abbrev number
1774 AssignAbbrev(Die->getAbbrev());
1775
1776 // Add the size of the abbreviation number to the output offset.
1777 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1778
1779 if (!Abbrev->hasChildren()) {
1780 // Update our size.
1781 Die->setSize(OutOffset - Die->getOffset());
1782 return Die;
1783 }
1784
1785 // Recursively clone children.
1786 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1787 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00001788 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001789 Die->addChild(std::unique_ptr<DIE>(Clone));
1790 OutOffset = Clone->getOffset() + Clone->getSize();
1791 }
1792 }
1793
1794 // Account for the end of children marker.
1795 OutOffset += sizeof(int8_t);
1796 // Update our size.
1797 Die->setSize(OutOffset - Die->getOffset());
1798 return Die;
1799}
1800
Frederic Riss25440872015-03-13 23:30:31 +00001801/// \brief Patch the input object file relevant debug_ranges entries
1802/// and emit them in the output file. Update the relevant attributes
1803/// to point at the new entries.
1804void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
1805 DWARFContext &OrigDwarf) const {
1806 DWARFDebugRangeList RangeList;
1807 const auto &FunctionRanges = Unit.getFunctionRanges();
1808 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
1809 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
1810 OrigDwarf.isLittleEndian(), AddressSize);
1811 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1812 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1813 const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
1814 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
1815 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1816 // Ranges addresses are based on the unit's low_pc. Compute the
1817 // offset we need to apply to adapt to the the new unit's low_pc.
1818 int64_t UnitPcOffset = 0;
1819 if (OrigLowPc != -1ULL)
1820 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
1821
1822 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
1823 uint32_t Offset = RangeAttribute->getValue();
1824 RangeAttribute->setValue(Streamer->getRangesSectionSize());
1825 RangeList.extract(RangeExtractor, &Offset);
1826 const auto &Entries = RangeList.getEntries();
1827 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
1828
1829 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
1830 First.StartAddress >= CurrRange.stop()) {
1831 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
1832 if (CurrRange == InvalidRange ||
1833 CurrRange.start() > First.StartAddress + OrigLowPc) {
1834 reportWarning("no mapping for range.");
1835 continue;
1836 }
1837 }
1838
1839 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
1840 AddressSize);
1841 }
1842}
1843
Frederic Riss563b1b02015-03-14 03:46:51 +00001844/// \brief Generate the debug_aranges entries for \p Unit and if the
1845/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
1846/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00001847/// FIXME: this could actually be done right in patchRangesForUnit,
1848/// but for the sake of initial bit-for-bit compatibility with legacy
1849/// dsymutil, we have to do it in a delayed pass.
1850void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Frederic Riss563b1b02015-03-14 03:46:51 +00001851 DIEInteger *Attr = Unit.getUnitRangesAttribute();
1852 if (Attr)
Frederic Riss25440872015-03-13 23:30:31 +00001853 Attr->setValue(Streamer->getRangesSectionSize());
Frederic Riss563b1b02015-03-14 03:46:51 +00001854 Streamer->emitUnitRangesEntries(Unit, Attr != nullptr);
Frederic Riss25440872015-03-13 23:30:31 +00001855}
1856
Frederic Rissd3455182015-01-28 18:27:01 +00001857bool DwarfLinker::link(const DebugMap &Map) {
1858
1859 if (Map.begin() == Map.end()) {
1860 errs() << "Empty debug map.\n";
1861 return false;
1862 }
1863
Frederic Rissc99ea202015-02-28 00:29:11 +00001864 if (!createStreamer(Map.getTriple(), OutputFilename))
1865 return false;
1866
Frederic Rissb8b43d52015-03-04 22:07:44 +00001867 // Size of the DIEs (and headers) generated for the linked output.
1868 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00001869 // A unique ID that identifies each compile unit.
1870 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00001871 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001872 CurrentDebugObject = Obj.get();
1873
Frederic Rissb9818322015-02-28 00:29:07 +00001874 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00001875 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1876 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1877 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001878 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00001879 continue;
1880 }
1881
Frederic Riss1036e642015-02-13 23:18:22 +00001882 // Look for relocations that correspond to debug map entries.
1883 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00001884 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00001885 outs() << "No valid relocations found. Skipping.\n";
1886 continue;
1887 }
1888
Frederic Riss563cba62015-01-28 22:15:14 +00001889 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00001890 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss563cba62015-01-28 22:15:14 +00001891 startDebugObject(DwarfContext);
Frederic Rissd3455182015-01-28 18:27:01 +00001892
Frederic Riss563cba62015-01-28 22:15:14 +00001893 // In a first phase, just read in the debug info and store the DIE
1894 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00001895 for (const auto &CU : DwarfContext.compile_units()) {
1896 auto *CUDie = CU->getCompileUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00001897 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00001898 outs() << "Input compilation unit:";
1899 CUDie->dump(outs(), CU.get(), 0);
1900 }
Frederic Riss3cced052015-03-14 03:46:40 +00001901 Units.emplace_back(*CU, UnitID++);
Frederic Riss9aa725b2015-02-13 23:18:31 +00001902 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00001903 }
Frederic Riss563cba62015-01-28 22:15:14 +00001904
Frederic Riss84c09a52015-02-13 23:18:34 +00001905 // Then mark all the DIEs that need to be present in the linked
1906 // output and collect some information about them. Note that this
1907 // loop can not be merged with the previous one becaue cross-cu
1908 // references require the ParentIdx to be setup for every CU in
1909 // the object file before calling this.
1910 for (auto &CurrentUnit : Units)
1911 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1912 CurrentUnit, 0);
1913
Frederic Riss23e20e92015-03-07 01:25:09 +00001914 // The calls to applyValidRelocs inside cloneDIE will walk the
1915 // reloc array again (in the same way findValidRelocsInDebugInfo()
1916 // did). We need to reset the NextValidReloc index to the beginning.
1917 NextValidReloc = 0;
1918
Frederic Rissb8b43d52015-03-04 22:07:44 +00001919 // Construct the output DIE tree by cloning the DIEs we chose to
1920 // keep above. If there are no valid relocs, then there's nothing
1921 // to clone/emit.
1922 if (!ValidRelocs.empty())
1923 for (auto &CurrentUnit : Units) {
1924 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00001925 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00001926 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
1927 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001928 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00001929 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss25440872015-03-13 23:30:31 +00001930 if (!OutputDIE || Options.NoOutput)
1931 continue;
1932 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00001933 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001934 }
1935
1936 // Emit all the compile unit's debug information.
1937 if (!ValidRelocs.empty() && !Options.NoOutput)
1938 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00001939 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00001940 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001941 Streamer->emitCompileUnitHeader(CurrentUnit);
1942 if (!CurrentUnit.getOutputUnitDIE())
1943 continue;
1944 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1945 }
1946
Frederic Riss563cba62015-01-28 22:15:14 +00001947 // Clean-up before starting working on the next object.
1948 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00001949 }
1950
Frederic Rissb8b43d52015-03-04 22:07:44 +00001951 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00001952 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001953 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00001954 Streamer->emitStrings(StringPool);
1955 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00001956
Frederic Rissc99ea202015-02-28 00:29:11 +00001957 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00001958}
1959}
Frederic Rissd3455182015-01-28 18:27:01 +00001960
Frederic Rissb9818322015-02-28 00:29:07 +00001961bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1962 const LinkOptions &Options) {
1963 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00001964 return Linker.link(DM);
1965}
1966}
Frederic Riss231f7142014-12-12 17:31:24 +00001967}