blob: 5c26f91079e9f9bad0b59360c8ef21e2affc9a07 [file] [log] [blame]
Frederic Riss231f7142014-12-12 17:31:24 +00001//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "DebugMap.h"
Frederic Rissd3455182015-01-28 18:27:01 +000010#include "BinaryHolder.h"
11#include "DebugMap.h"
Frederic Riss231f7142014-12-12 17:31:24 +000012#include "dsymutil.h"
Frederic Riss1af75f72015-03-12 18:45:10 +000013#include "llvm/ADT/IntervalMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000014#include "llvm/ADT/StringMap.h"
15#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000016#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000017#include "llvm/CodeGen/DIE.h"
Zachary Turner82af9432015-01-30 18:07:45 +000018#include "llvm/DebugInfo/DWARF/DWARFContext.h"
19#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000020#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000021#include "llvm/MC/MCAsmBackend.h"
22#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000025#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000026#include "llvm/MC/MCInstrInfo.h"
27#include "llvm/MC/MCObjectFileInfo.h"
28#include "llvm/MC/MCRegisterInfo.h"
29#include "llvm/MC/MCStreamer.h"
Frederic Riss1036e642015-02-13 23:18:22 +000030#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000031#include "llvm/Support/Dwarf.h"
32#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000033#include "llvm/Support/TargetRegistry.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000036#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000037#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000038
39namespace llvm {
40namespace dsymutil {
41
Frederic Rissd3455182015-01-28 18:27:01 +000042namespace {
43
Frederic Rissdef4fb72015-02-28 00:29:01 +000044void warn(const Twine &Warning, const Twine &Context) {
45 errs() << Twine("while processing ") + Context + ":\n";
46 errs() << Twine("warning: ") + Warning + "\n";
47}
48
Frederic Rissc99ea202015-02-28 00:29:11 +000049bool error(const Twine &Error, const Twine &Context) {
50 errs() << Twine("while processing ") + Context + ":\n";
51 errs() << Twine("error: ") + Error + "\n";
52 return false;
53}
54
Frederic Riss1af75f72015-03-12 18:45:10 +000055template <typename KeyT, typename ValT>
56using HalfOpenIntervalMap =
57 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
58 IntervalMapHalfOpenInfo<KeyT>>;
59
Frederic Riss25440872015-03-13 23:30:31 +000060typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
61
Frederic Riss563cba62015-01-28 22:15:14 +000062/// \brief Stores all information relating to a compile unit, be it in
63/// its original instance in the object file to its brand new cloned
64/// and linked DIE tree.
65class CompileUnit {
66public:
67 /// \brief Information gathered about a DIE in the object file.
68 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +000069 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss9833de62015-03-06 23:22:53 +000070 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +000071 uint32_t ParentIdx; ///< The index of this DIE's parent.
72 bool Keep; ///< Is the DIE part of the linked output?
73 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +000074 };
75
Frederic Riss3cced052015-03-14 03:46:40 +000076 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
77 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Frederic Riss25440872015-03-13 23:30:31 +000078 Ranges(RangeAlloc), UnitRangeAttribute(nullptr) {
Frederic Riss563cba62015-01-28 22:15:14 +000079 Info.resize(OrigUnit.getNumDIEs());
80 }
81
Frederic Riss2838f9e2015-03-05 05:29:05 +000082 CompileUnit(CompileUnit &&RHS)
83 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
84 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +000085 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
86 // The CompileUnit container has been 'reserve()'d with the right
87 // size. We cannot move the IntervalMap anyway.
88 llvm_unreachable("CompileUnits should not be moved.");
89 }
David Blaikiea8adc132015-03-04 22:20:52 +000090
Frederic Rissc3349d42015-02-13 23:18:27 +000091 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +000092
Frederic Riss3cced052015-03-14 03:46:40 +000093 unsigned getUniqueID() const { return ID; }
94
Frederic Rissb8b43d52015-03-04 22:07:44 +000095 DIE *getOutputUnitDIE() const { return CUDie.get(); }
96 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
97
Frederic Riss563cba62015-01-28 22:15:14 +000098 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
99 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
100
Frederic Rissb8b43d52015-03-04 22:07:44 +0000101 uint64_t getStartOffset() const { return StartOffset; }
102 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000103 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000104
Frederic Riss5a62dc32015-03-13 18:35:54 +0000105 uint64_t getLowPc() const { return LowPc; }
106 uint64_t getHighPc() const { return HighPc; }
107
Frederic Riss25440872015-03-13 23:30:31 +0000108 DIEInteger *getUnitRangesAttribute() const { return UnitRangeAttribute; }
109 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
110 const std::vector<DIEInteger *> &getRangesAttributes() const {
111 return RangeAttributes;
112 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000113
Frederic Rissdfb97902015-03-14 15:49:07 +0000114 const std::vector<std::pair<DIEInteger *, int64_t>> &
115 getLocationAttributes() const {
116 return LocationAttributes;
117 }
118
Frederic Riss9d441b62015-03-06 23:22:50 +0000119 /// \brief Compute the end offset for this unit. Must be
120 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000121 /// \returns the next unit offset (which is also the current
122 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000123 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000124
Frederic Riss6afcfce2015-03-13 18:35:57 +0000125 /// \brief Keep track of a forward reference to DIE \p Die in \p
126 /// RefUnit by \p Attr. The attribute should be fixed up later to
127 /// point to the absolute offset of \p Die in the debug_info section.
128 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
129 DIEInteger *Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000130
131 /// \brief Apply all fixups recored by noteForwardReference().
132 void fixupForwardReferences();
133
Frederic Riss1af75f72015-03-12 18:45:10 +0000134 /// \brief Add a function range [\p LowPC, \p HighPC) that is
135 /// relocatad by applying offset \p PCOffset.
136 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
137
Frederic Riss5c9c7062015-03-13 23:55:29 +0000138 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000139 /// patch up later.
140 void noteRangeAttribute(const DIE &Die, DIEInteger *Attr);
141
Frederic Rissdfb97902015-03-14 15:49:07 +0000142 /// \brief Keep track of a location attribute pointing to a location
143 /// list in the debug_loc section.
144 void noteLocationAttribute(DIEInteger *Attr, int64_t PcOffset);
145
Frederic Riss563cba62015-01-28 22:15:14 +0000146private:
147 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000148 unsigned ID;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000149 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
150 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
151
152 uint64_t StartOffset;
153 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000154
Frederic Riss5a62dc32015-03-13 18:35:54 +0000155 uint64_t LowPc;
156 uint64_t HighPc;
157
Frederic Riss9833de62015-03-06 23:22:53 +0000158 /// \brief A list of attributes to fixup with the absolute offset of
159 /// a DIE in the debug_info section.
160 ///
161 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000162 /// cloning because for cross-cu forward refences the target DIE's
163 /// offset isn't known you emit the reference attribute.
164 std::vector<std::tuple<DIE *, const CompileUnit *, DIEInteger *>>
165 ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000166
Frederic Riss25440872015-03-13 23:30:31 +0000167 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000168 /// \brief The ranges in that interval map are the PC ranges for
169 /// functions in this unit, associated with the PC offset to apply
170 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000171 FunctionIntervals Ranges;
172
173 /// \brief DW_AT_ranges attributes to patch after we have gathered
174 /// all the unit's function addresses.
175 /// @{
176 std::vector<DIEInteger *> RangeAttributes;
177 DIEInteger *UnitRangeAttribute;
178 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000179
180 /// \brief Location attributes that need to be transfered from th
181 /// original debug_loc section to the liked one. They are stored
182 /// along with the PC offset that is to be applied to their
183 /// function's address.
184 std::vector<std::pair<DIEInteger *, int64_t>> LocationAttributes;
Frederic Riss563cba62015-01-28 22:15:14 +0000185};
186
Frederic Riss9d441b62015-03-06 23:22:50 +0000187uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000188 NextUnitOffset = StartOffset + 11 /* Header size */;
189 // The root DIE might be null, meaning that the Unit had nothing to
190 // contribute to the linked output. In that case, we will emit the
191 // unit header without any actual DIE.
192 if (CUDie)
193 NextUnitOffset += CUDie->getSize();
194 return NextUnitOffset;
195}
196
Frederic Riss6afcfce2015-03-13 18:35:57 +0000197/// \brief Keep track of a forward cross-cu reference from this unit
198/// to \p Die that lives in \p RefUnit.
199void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
200 DIEInteger *Attr) {
201 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000202}
203
204/// \brief Apply all fixups recorded by noteForwardReference().
205void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000206 for (const auto &Ref : ForwardDIEReferences) {
207 DIE *RefDie;
208 const CompileUnit *RefUnit;
209 DIEInteger *Attr;
210 std::tie(RefDie, RefUnit, Attr) = Ref;
211 Attr->setValue(RefDie->getOffset() + RefUnit->getStartOffset());
212 }
Frederic Riss9833de62015-03-06 23:22:53 +0000213}
214
Frederic Riss5a62dc32015-03-13 18:35:54 +0000215void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
216 int64_t PcOffset) {
217 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
218 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
219 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000220}
221
Frederic Riss25440872015-03-13 23:30:31 +0000222void CompileUnit::noteRangeAttribute(const DIE &Die, DIEInteger *Attr) {
223 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
224 RangeAttributes.push_back(Attr);
225 else
226 UnitRangeAttribute = Attr;
227}
228
Frederic Rissdfb97902015-03-14 15:49:07 +0000229void CompileUnit::noteLocationAttribute(DIEInteger *Attr, int64_t PcOffset) {
230 LocationAttributes.emplace_back(Attr, PcOffset);
231}
232
Frederic Rissef648462015-03-06 17:56:30 +0000233/// \brief A string table that doesn't need relocations.
234///
235/// We are doing a final link, no need for a string table that
236/// has relocation entries for every reference to it. This class
237/// provides this ablitity by just associating offsets with
238/// strings.
239class NonRelocatableStringpool {
240public:
241 /// \brief Entries are stored into the StringMap and simply linked
242 /// together through the second element of this pair in order to
243 /// keep track of insertion order.
244 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
245 MapTy;
246
247 NonRelocatableStringpool()
248 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
249 // Legacy dsymutil puts an empty string at the start of the line
250 // table.
251 getStringOffset("");
252 }
253
254 /// \brief Get the offset of string \p S in the string table. This
255 /// can insert a new element or return the offset of a preexisitng
256 /// one.
257 uint32_t getStringOffset(StringRef S);
258
259 /// \brief Get permanent storage for \p S (but do not necessarily
260 /// emit \p S in the output section).
261 /// \returns The StringRef that points to permanent storage to use
262 /// in place of \p S.
263 StringRef internString(StringRef S);
264
265 // \brief Return the first entry of the string table.
266 const MapTy::MapEntryTy *getFirstEntry() const {
267 return getNextEntry(&Sentinel);
268 }
269
270 // \brief Get the entry following \p E in the string table or null
271 // if \p E was the last entry.
272 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
273 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
274 }
275
276 uint64_t getSize() { return CurrentEndOffset; }
277
278private:
279 MapTy Strings;
280 uint32_t CurrentEndOffset;
281 MapTy::MapEntryTy Sentinel, *Last;
282};
283
284/// \brief Get the offset of string \p S in the string table. This
285/// can insert a new element or return the offset of a preexisitng
286/// one.
287uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
288 if (S.empty() && !Strings.empty())
289 return 0;
290
291 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
292 MapTy::iterator It;
293 bool Inserted;
294
295 // A non-empty string can't be at offset 0, so if we have an entry
296 // with a 0 offset, it must be a previously interned string.
297 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
298 if (Inserted || It->getValue().first == 0) {
299 // Set offset and chain at the end of the entries list.
300 It->getValue().first = CurrentEndOffset;
301 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
302 Last->getValue().second = &*It;
303 Last = &*It;
304 }
305 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000306}
Frederic Rissef648462015-03-06 17:56:30 +0000307
308/// \brief Put \p S into the StringMap so that it gets permanent
309/// storage, but do not actually link it in the chain of elements
310/// that go into the output section. A latter call to
311/// getStringOffset() with the same string will chain it though.
312StringRef NonRelocatableStringpool::internString(StringRef S) {
313 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
314 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
315 return InsertResult.first->getKey();
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000316}
Frederic Rissef648462015-03-06 17:56:30 +0000317
Frederic Rissc99ea202015-02-28 00:29:11 +0000318/// \brief The Dwarf streaming logic
319///
320/// All interactions with the MC layer that is used to build the debug
321/// information binary representation are handled in this class.
322class DwarfStreamer {
323 /// \defgroup MCObjects MC layer objects constructed by the streamer
324 /// @{
325 std::unique_ptr<MCRegisterInfo> MRI;
326 std::unique_ptr<MCAsmInfo> MAI;
327 std::unique_ptr<MCObjectFileInfo> MOFI;
328 std::unique_ptr<MCContext> MC;
329 MCAsmBackend *MAB; // Owned by MCStreamer
330 std::unique_ptr<MCInstrInfo> MII;
331 std::unique_ptr<MCSubtargetInfo> MSTI;
332 MCCodeEmitter *MCE; // Owned by MCStreamer
333 MCStreamer *MS; // Owned by AsmPrinter
334 std::unique_ptr<TargetMachine> TM;
335 std::unique_ptr<AsmPrinter> Asm;
336 /// @}
337
338 /// \brief the file we stream the linked Dwarf to.
339 std::unique_ptr<raw_fd_ostream> OutFile;
340
Frederic Riss25440872015-03-13 23:30:31 +0000341 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000342 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000343 uint32_t LineSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000344
Frederic Rissc99ea202015-02-28 00:29:11 +0000345public:
346 /// \brief Actually create the streamer and the ouptut file.
347 ///
348 /// This could be done directly in the constructor, but it feels
349 /// more natural to handle errors through return value.
350 bool init(Triple TheTriple, StringRef OutputFilename);
351
Frederic Rissb8b43d52015-03-04 22:07:44 +0000352 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000353 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000354
355 AsmPrinter &getAsmPrinter() const { return *Asm; }
356
357 /// \brief Set the current output section to debug_info and change
358 /// the MC Dwarf version to \p DwarfVersion.
359 void switchToDebugInfoSection(unsigned DwarfVersion);
360
361 /// \brief Emit the compilation unit header for \p Unit in the
362 /// debug_info section.
363 ///
364 /// As a side effect, this also switches the current Dwarf version
365 /// of the MC layer to the one of U.getOrigUnit().
366 void emitCompileUnitHeader(CompileUnit &Unit);
367
368 /// \brief Recursively emit the DIE tree rooted at \p Die.
369 void emitDIE(DIE &Die);
370
371 /// \brief Emit the abbreviation table \p Abbrevs to the
372 /// debug_abbrev section.
373 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000374
375 /// \brief Emit the string table described by \p Pool.
376 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000377
378 /// \brief Emit debug_ranges for \p FuncRange by translating the
379 /// original \p Entries.
380 void emitRangesEntries(
381 int64_t UnitPcOffset, uint64_t OrigLowPc,
382 FunctionIntervals::const_iterator FuncRange,
383 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
384 unsigned AddressSize);
385
Frederic Riss563b1b02015-03-14 03:46:51 +0000386 /// \brief Emit debug_aranges entries for \p Unit and if \p
387 /// DoRangesSection is true, also emit the debug_ranges entries for
388 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
389 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000390
391 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000392
393 /// \brief Emit the debug_loc contribution for \p Unit by copying
394 /// the entries from \p Dwarf and offseting them. Update the
395 /// location attributes to point to the new entries.
396 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000397
398 /// \brief Emit the line table described in \p Rows into the
399 /// debug_line section.
400 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
401 std::vector<DWARFDebugLine::Row> &Rows,
402 unsigned AdddressSize);
403
404 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000405};
406
407bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
408 std::string ErrorStr;
409 std::string TripleName;
410 StringRef Context = "dwarf streamer init";
411
412 // Get the target.
413 const Target *TheTarget =
414 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
415 if (!TheTarget)
416 return error(ErrorStr, Context);
417 TripleName = TheTriple.getTriple();
418
419 // Create all the MC Objects.
420 MRI.reset(TheTarget->createMCRegInfo(TripleName));
421 if (!MRI)
422 return error(Twine("no register info for target ") + TripleName, Context);
423
424 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
425 if (!MAI)
426 return error("no asm info for target " + TripleName, Context);
427
428 MOFI.reset(new MCObjectFileInfo);
429 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
430 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
431 *MC);
432
433 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
434 if (!MAB)
435 return error("no asm backend for target " + TripleName, Context);
436
437 MII.reset(TheTarget->createMCInstrInfo());
438 if (!MII)
439 return error("no instr info info for target " + TripleName, Context);
440
441 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
442 if (!MSTI)
443 return error("no subtarget info for target " + TripleName, Context);
444
Eric Christopher0169e422015-03-10 22:03:14 +0000445 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000446 if (!MCE)
447 return error("no code emitter for target " + TripleName, Context);
448
449 // Create the output file.
450 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000451 OutFile =
452 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000453 if (EC)
454 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
455
456 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
457 *MSTI, false);
458 if (!MS)
459 return error("no object streamer for target " + TripleName, Context);
460
461 // Finally create the AsmPrinter we'll use to emit the DIEs.
462 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
463 if (!TM)
464 return error("no target machine for target " + TripleName, Context);
465
466 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
467 if (!Asm)
468 return error("no asm printer for target " + TripleName, Context);
469
Frederic Riss25440872015-03-13 23:30:31 +0000470 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000471 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000472 LineSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000473
Frederic Rissc99ea202015-02-28 00:29:11 +0000474 return true;
475}
476
477bool DwarfStreamer::finish() {
478 MS->Finish();
479 return true;
480}
481
Frederic Rissb8b43d52015-03-04 22:07:44 +0000482/// \brief Set the current output section to debug_info and change
483/// the MC Dwarf version to \p DwarfVersion.
484void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
485 MS->SwitchSection(MOFI->getDwarfInfoSection());
486 MC->setDwarfVersion(DwarfVersion);
487}
488
489/// \brief Emit the compilation unit header for \p Unit in the
490/// debug_info section.
491///
492/// A Dwarf scetion header is encoded as:
493/// uint32_t Unit length (omiting this field)
494/// uint16_t Version
495/// uint32_t Abbreviation table offset
496/// uint8_t Address size
497///
498/// Leading to a total of 11 bytes.
499void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
500 unsigned Version = Unit.getOrigUnit().getVersion();
501 switchToDebugInfoSection(Version);
502
503 // Emit size of content not including length itself. The size has
504 // already been computed in CompileUnit::computeOffsets(). Substract
505 // 4 to that size to account for the length field.
506 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
507 Asm->EmitInt16(Version);
508 // We share one abbreviations table across all units so it's always at the
509 // start of the section.
510 Asm->EmitInt32(0);
511 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
512}
513
514/// \brief Emit the \p Abbrevs array as the shared abbreviation table
515/// for the linked Dwarf file.
516void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
517 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
518 Asm->emitDwarfAbbrevs(Abbrevs);
519}
520
521/// \brief Recursively emit the DIE tree rooted at \p Die.
522void DwarfStreamer::emitDIE(DIE &Die) {
523 MS->SwitchSection(MOFI->getDwarfInfoSection());
524 Asm->emitDwarfDIE(Die);
525}
526
Frederic Rissef648462015-03-06 17:56:30 +0000527/// \brief Emit the debug_str section stored in \p Pool.
528void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
529 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
530 for (auto *Entry = Pool.getFirstEntry(); Entry;
531 Entry = Pool.getNextEntry(Entry))
532 Asm->OutStreamer.EmitBytes(
533 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
534}
535
Frederic Riss25440872015-03-13 23:30:31 +0000536/// \brief Emit the debug_range section contents for \p FuncRange by
537/// translating the original \p Entries. The debug_range section
538/// format is totally trivial, consisting just of pairs of address
539/// sized addresses describing the ranges.
540void DwarfStreamer::emitRangesEntries(
541 int64_t UnitPcOffset, uint64_t OrigLowPc,
542 FunctionIntervals::const_iterator FuncRange,
543 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
544 unsigned AddressSize) {
545 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
546
547 // Offset each range by the right amount.
548 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
549 for (const auto &Range : Entries) {
550 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
551 warn("unsupported base address selection operation",
552 "emitting debug_ranges");
553 break;
554 }
555 // Do not emit empty ranges.
556 if (Range.StartAddress == Range.EndAddress)
557 continue;
558
559 // All range entries should lie in the function range.
560 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
561 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
562 warn("inconsistent range data.", "emitting debug_ranges");
563 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
564 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
565 RangesSectionSize += 2 * AddressSize;
566 }
567
568 // Add the terminator entry.
569 MS->EmitIntValue(0, AddressSize);
570 MS->EmitIntValue(0, AddressSize);
571 RangesSectionSize += 2 * AddressSize;
572}
573
Frederic Riss563b1b02015-03-14 03:46:51 +0000574/// \brief Emit the debug_aranges contribution of a unit and
575/// if \p DoDebugRanges is true the debug_range contents for a
576/// compile_unit level DW_AT_ranges attribute (Which are basically the
577/// same thing with a different base address).
578/// Just aggregate all the ranges gathered inside that unit.
579void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
580 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000581 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
582 // Gather the ranges in a vector, so that we can simplify them. The
583 // IntervalMap will have coalesced the non-linked ranges, but here
584 // we want to coalesce the linked addresses.
585 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
586 const auto &FunctionRanges = Unit.getFunctionRanges();
587 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
588 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000589 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
590 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000591
592 // The object addresses where sorted, but again, the linked
593 // addresses might end up in a different order.
594 std::sort(Ranges.begin(), Ranges.end());
595
Frederic Riss563b1b02015-03-14 03:46:51 +0000596 if (!Ranges.empty()) {
597 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
598
599 MCSymbol *BeginLabel = Asm->GetTempSymbol("Barange", Unit.getUniqueID());
600 MCSymbol *EndLabel = Asm->GetTempSymbol("Earange", Unit.getUniqueID());
601
602 unsigned HeaderSize =
603 sizeof(int32_t) + // Size of contents (w/o this field
604 sizeof(int16_t) + // DWARF ARange version number
605 sizeof(int32_t) + // Offset of CU in the .debug_info section
606 sizeof(int8_t) + // Pointer Size (in bytes)
607 sizeof(int8_t); // Segment Size (in bytes)
608
609 unsigned TupleSize = AddressSize * 2;
610 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
611
612 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
613 Asm->OutStreamer.EmitLabel(BeginLabel);
614 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
615 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
616 Asm->EmitInt8(AddressSize); // Address size
617 Asm->EmitInt8(0); // Segment size
618
619 Asm->OutStreamer.EmitFill(Padding, 0x0);
620
621 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
622 ++Range) {
623 uint64_t RangeStart = Range->first;
624 MS->EmitIntValue(RangeStart, AddressSize);
625 while ((Range + 1) != End && Range->second == (Range + 1)->first)
626 ++Range;
627 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
628 }
629
630 // Emit terminator
631 Asm->OutStreamer.EmitIntValue(0, AddressSize);
632 Asm->OutStreamer.EmitIntValue(0, AddressSize);
633 Asm->OutStreamer.EmitLabel(EndLabel);
634 }
635
636 if (!DoDebugRanges)
637 return;
638
639 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
640 // Offset each range by the right amount.
641 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000642 // Emit coalesced ranges.
643 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000644 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000645 while (Range + 1 != End && Range->second == (Range + 1)->first)
646 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000647 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000648 RangesSectionSize += 2 * AddressSize;
649 }
650
651 // Add the terminator entry.
652 MS->EmitIntValue(0, AddressSize);
653 MS->EmitIntValue(0, AddressSize);
654 RangesSectionSize += 2 * AddressSize;
655}
656
Frederic Rissdfb97902015-03-14 15:49:07 +0000657/// \brief Emit location lists for \p Unit and update attribtues to
658/// point to the new entries.
659void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
660 DWARFContext &Dwarf) {
661 const std::vector<std::pair<DIEInteger *, int64_t>> &Attributes =
662 Unit.getLocationAttributes();
663
664 if (Attributes.empty())
665 return;
666
667 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
668
669 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
670 const DWARFSection &InputSec = Dwarf.getLocSection();
671 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
672 DWARFUnit &OrigUnit = Unit.getOrigUnit();
673 const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
674 int64_t UnitPcOffset = 0;
675 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
676 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
677 if (OrigLowPc != -1ULL)
678 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
679
680 for (const auto &Attr : Attributes) {
681 uint32_t Offset = Attr.first->getValue();
682 Attr.first->setValue(LocSectionSize);
683 // This is the quantity to add to the old location address to get
684 // the correct address for the new one.
685 int64_t LocPcOffset = Attr.second + UnitPcOffset;
686 while (Data.isValidOffset(Offset)) {
687 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
688 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
689 LocSectionSize += 2 * AddressSize;
690 if (Low == 0 && High == 0) {
691 Asm->OutStreamer.EmitIntValue(0, AddressSize);
692 Asm->OutStreamer.EmitIntValue(0, AddressSize);
693 break;
694 }
695 Asm->OutStreamer.EmitIntValue(Low + LocPcOffset, AddressSize);
696 Asm->OutStreamer.EmitIntValue(High + LocPcOffset, AddressSize);
697 uint64_t Length = Data.getU16(&Offset);
698 Asm->OutStreamer.EmitIntValue(Length, 2);
699 // Just copy the bytes over.
700 Asm->OutStreamer.EmitBytes(
701 StringRef(InputSec.Data.substr(Offset, Length)));
702 Offset += Length;
703 LocSectionSize += Length + 2;
704 }
705 }
706}
707
Frederic Riss63786b02015-03-15 20:45:43 +0000708void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
709 unsigned MinInstLength,
710 std::vector<DWARFDebugLine::Row> &Rows,
711 unsigned PointerSize) {
712 // Switch to the section where the table will be emitted into.
713 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
714 MCSymbol *LineStartSym = MC->CreateTempSymbol();
715 MCSymbol *LineEndSym = MC->CreateTempSymbol();
716
717 // The first 4 bytes is the total length of the information for this
718 // compilation unit (not including these 4 bytes for the length).
719 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
720 Asm->OutStreamer.EmitLabel(LineStartSym);
721 // Copy Prologue.
722 MS->EmitBytes(PrologueBytes);
723 LineSectionSize += PrologueBytes.size() + 4;
724
Frederic Rissc3820d02015-03-15 22:20:28 +0000725 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000726 raw_svector_ostream EncodingOS(EncodingBuffer);
727
728 if (Rows.empty()) {
729 // We only have the dummy entry, dsymutil emits an entry with a 0
730 // address in that case.
731 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
732 MS->EmitBytes(EncodingOS.str());
733 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000734 MS->EmitLabel(LineEndSym);
735 return;
736 }
737
738 // Line table state machine fields
739 unsigned FileNum = 1;
740 unsigned LastLine = 1;
741 unsigned Column = 0;
742 unsigned IsStatement = 1;
743 unsigned Isa = 0;
744 uint64_t Address = -1ULL;
745
746 unsigned RowsSinceLastSequence = 0;
747
748 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
749 auto &Row = Rows[Idx];
750
751 int64_t AddressDelta;
752 if (Address == -1ULL) {
753 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
754 MS->EmitULEB128IntValue(PointerSize + 1);
755 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
756 MS->EmitIntValue(Row.Address, PointerSize);
757 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
758 AddressDelta = 0;
759 } else {
760 AddressDelta = (Row.Address - Address) / MinInstLength;
761 }
762
763 // FIXME: code copied and transfromed from
764 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
765 // this code, but the current compatibility requirement with
766 // classic dsymutil makes it hard. Revisit that once this
767 // requirement is dropped.
768
769 if (FileNum != Row.File) {
770 FileNum = Row.File;
771 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
772 MS->EmitULEB128IntValue(FileNum);
773 LineSectionSize += 1 + getULEB128Size(FileNum);
774 }
775 if (Column != Row.Column) {
776 Column = Row.Column;
777 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
778 MS->EmitULEB128IntValue(Column);
779 LineSectionSize += 1 + getULEB128Size(Column);
780 }
781
782 // FIXME: We should handle the discriminator here, but dsymutil
783 // doesn' consider it, thus ignore it for now.
784
785 if (Isa != Row.Isa) {
786 Isa = Row.Isa;
787 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
788 MS->EmitULEB128IntValue(Isa);
789 LineSectionSize += 1 + getULEB128Size(Isa);
790 }
791 if (IsStatement != Row.IsStmt) {
792 IsStatement = Row.IsStmt;
793 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
794 LineSectionSize += 1;
795 }
796 if (Row.BasicBlock) {
797 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
798 LineSectionSize += 1;
799 }
800
801 if (Row.PrologueEnd) {
802 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
803 LineSectionSize += 1;
804 }
805
806 if (Row.EpilogueBegin) {
807 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
808 LineSectionSize += 1;
809 }
810
811 int64_t LineDelta = int64_t(Row.Line) - LastLine;
812 if (!Row.EndSequence) {
813 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
814 MS->EmitBytes(EncodingOS.str());
815 LineSectionSize += EncodingBuffer.size();
816 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000817 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000818 Address = Row.Address;
819 LastLine = Row.Line;
820 RowsSinceLastSequence++;
821 } else {
822 if (LineDelta) {
823 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
824 MS->EmitSLEB128IntValue(LineDelta);
825 LineSectionSize += 1 + getSLEB128Size(LineDelta);
826 }
827 if (AddressDelta) {
828 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
829 MS->EmitULEB128IntValue(AddressDelta);
830 LineSectionSize += 1 + getULEB128Size(AddressDelta);
831 }
832 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
833 MS->EmitBytes(EncodingOS.str());
834 LineSectionSize += EncodingBuffer.size();
835 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000836 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000837 Address = -1ULL;
838 LastLine = FileNum = IsStatement = 1;
839 RowsSinceLastSequence = Column = Isa = 0;
840 }
841 }
842
843 if (RowsSinceLastSequence) {
844 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
845 MS->EmitBytes(EncodingOS.str());
846 LineSectionSize += EncodingBuffer.size();
847 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000848 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000849 }
850
851 MS->EmitLabel(LineEndSym);
852}
853
Frederic Rissd3455182015-01-28 18:27:01 +0000854/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000855///
856/// The link of the dwarf information from the object files will be
857/// driven by the selection of 'root DIEs', which are DIEs that
858/// describe variables or functions that are present in the linked
859/// binary (and thus have entries in the debug map). All the debug
860/// information that will be linked (the DIEs, but also the line
861/// tables, ranges, ...) is derived from that set of root DIEs.
862///
863/// The root DIEs are identified because they contain relocations that
864/// correspond to a debug map entry at specific places (the low_pc for
865/// a function, the location for a variable). These relocations are
866/// called ValidRelocs in the DwarfLinker and are gathered as a very
867/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +0000868class DwarfLinker {
869public:
Frederic Rissb9818322015-02-28 00:29:07 +0000870 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
871 : OutputFilename(OutputFilename), Options(Options),
872 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +0000873
Frederic Rissb8b43d52015-03-04 22:07:44 +0000874 ~DwarfLinker() {
875 for (auto *Abbrev : Abbreviations)
876 delete Abbrev;
877 }
878
Frederic Rissd3455182015-01-28 18:27:01 +0000879 /// \brief Link the contents of the DebugMap.
880 bool link(const DebugMap &);
881
882private:
Frederic Riss563cba62015-01-28 22:15:14 +0000883 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +0000884 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +0000885
886 /// \brief Called at the end of a debug object link.
887 void endDebugObject();
888
Frederic Riss1036e642015-02-13 23:18:22 +0000889 /// \defgroup FindValidRelocations Translate debug map into a list
890 /// of relevant relocations
891 ///
892 /// @{
893 struct ValidReloc {
894 uint32_t Offset;
895 uint32_t Size;
896 uint64_t Addend;
897 const DebugMapObject::DebugMapEntry *Mapping;
898
899 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
900 const DebugMapObject::DebugMapEntry *Mapping)
901 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
902
903 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
904 };
905
906 /// \brief The valid relocations for the current DebugMapObject.
907 /// This vector is sorted by relocation offset.
908 std::vector<ValidReloc> ValidRelocs;
909
910 /// \brief Index into ValidRelocs of the next relocation to
911 /// consider. As we walk the DIEs in acsending file offset and as
912 /// ValidRelocs is sorted by file offset, keeping this index
913 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +0000914 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +0000915 unsigned NextValidReloc;
916
917 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
918 const DebugMapObject &DMO);
919
920 bool findValidRelocs(const object::SectionRef &Section,
921 const object::ObjectFile &Obj,
922 const DebugMapObject &DMO);
923
924 void findValidRelocsMachO(const object::SectionRef &Section,
925 const object::MachOObjectFile &Obj,
926 const DebugMapObject &DMO);
927 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +0000928
Frederic Riss84c09a52015-02-13 23:18:34 +0000929 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
930 ///
931 /// @{
932 /// \brief Recursively walk the \p DIE tree and look for DIEs to
933 /// keep. Store that information in \p CU's DIEInfo.
934 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
935 const DebugMapObject &DMO, CompileUnit &CU,
936 unsigned Flags);
937
938 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
939 enum TravesalFlags {
940 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
941 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
942 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
943 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
944 };
945
946 /// \brief Mark the passed DIE as well as all the ones it depends on
947 /// as kept.
948 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
949 CompileUnit::DIEInfo &MyInfo,
950 const DebugMapObject &DMO, CompileUnit &CU,
951 unsigned Flags);
952
953 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
954 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
955 unsigned Flags);
956
957 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
958 CompileUnit &Unit,
959 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
960
961 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
962 CompileUnit &Unit,
963 CompileUnit::DIEInfo &MyInfo,
964 unsigned Flags);
965
966 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
967 CompileUnit::DIEInfo &Info);
968 /// @}
969
Frederic Rissb8b43d52015-03-04 22:07:44 +0000970 /// \defgroup Linking Methods used to link the debug information
971 ///
972 /// @{
973 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
974 /// where useless (as decided by lookForDIEsToKeep()) bits have been
975 /// stripped out and addresses have been rewritten according to the
976 /// debug map.
977 ///
978 /// \param OutOffset is the offset the cloned DIE in the output
979 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +0000980 /// \param PCOffset (while cloning a function scope) is the offset
981 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000982 ///
983 /// \returns the root of the cloned tree.
984 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +0000985 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000986
987 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
988
Frederic Riss31da3242015-03-11 18:45:52 +0000989 /// \brief Information gathered and exchanged between the various
990 /// clone*Attributes helpers about the attributes of a particular DIE.
991 struct AttributesInfo {
992 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
993 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
994
995 AttributesInfo() : OrigHighPc(0), PCOffset(0) {}
996 };
997
Frederic Rissb8b43d52015-03-04 22:07:44 +0000998 /// \brief Helper for cloneDIE.
999 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1000 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001001 const AttributeSpec AttrSpec, unsigned AttrSize,
1002 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001003
1004 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001005 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1006 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001007
1008 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001009 unsigned
1010 cloneDieReferenceAttribute(DIE &Die,
1011 const DWARFDebugInfoEntryMinimal &InputDIE,
1012 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001013 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001014
1015 /// \brief Helper for cloneDIE.
1016 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1017 const DWARFFormValue &Val, unsigned AttrSize);
1018
1019 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001020 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1021 const DWARFFormValue &Val,
1022 const CompileUnit &Unit, AttributesInfo &Info);
1023
1024 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001025 unsigned cloneScalarAttribute(DIE &Die,
1026 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001027 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001028 const DWARFFormValue &Val, unsigned AttrSize,
1029 const AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001030
Frederic Riss23e20e92015-03-07 01:25:09 +00001031 /// \brief Helper for cloneDIE.
1032 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1033 bool isLittleEndian);
1034
Frederic Rissb8b43d52015-03-04 22:07:44 +00001035 /// \brief Assign an abbreviation number to \p Abbrev
1036 void AssignAbbrev(DIEAbbrev &Abbrev);
1037
1038 /// \brief FoldingSet that uniques the abbreviations.
1039 FoldingSet<DIEAbbrev> AbbreviationsSet;
1040 /// \brief Storage for the unique Abbreviations.
1041 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1042 /// be changed to a vecot of unique_ptrs.
1043 std::vector<DIEAbbrev *> Abbreviations;
1044
Frederic Riss25440872015-03-13 23:30:31 +00001045 /// \brief Compute and emit debug_ranges section for \p Unit, and
1046 /// patch the attributes referencing it.
1047 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1048
1049 /// \brief Generate and emit the DW_AT_ranges attribute for a
1050 /// compile_unit if it had one.
1051 void generateUnitRanges(CompileUnit &Unit) const;
1052
Frederic Riss63786b02015-03-15 20:45:43 +00001053 /// \brief Extract the line tables fromt he original dwarf, extract
1054 /// the relevant parts according to the linked function ranges and
1055 /// emit the result in the debug_line section.
1056 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1057
Frederic Rissb8b43d52015-03-04 22:07:44 +00001058 /// \brief DIELoc objects that need to be destructed (but not freed!).
1059 std::vector<DIELoc *> DIELocs;
1060 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1061 std::vector<DIEBlock *> DIEBlocks;
1062 /// \brief Allocator used for all the DIEValue objects.
1063 BumpPtrAllocator DIEAlloc;
1064 /// @}
1065
Frederic Riss1b9da422015-02-13 23:18:29 +00001066 /// \defgroup Helpers Various helper methods.
1067 ///
1068 /// @{
1069 const DWARFDebugInfoEntryMinimal *
1070 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1071 const DWARFDebugInfoEntryMinimal &DIE,
1072 CompileUnit *&ReferencedCU);
1073
1074 CompileUnit *getUnitForOffset(unsigned Offset);
1075
1076 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001077 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001078
1079 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +00001080 /// @}
1081
Frederic Riss563cba62015-01-28 22:15:14 +00001082private:
Frederic Rissd3455182015-01-28 18:27:01 +00001083 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001084 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001085 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001086 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001087
1088 /// The units of the current debug map object.
1089 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001090
1091 /// The debug map object curently under consideration.
1092 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001093
1094 /// \brief The Dwarf string pool
1095 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001096
1097 /// \brief This map is keyed by the entry PC of functions in that
1098 /// debug object and the associated value is a pair storing the
1099 /// corresponding end PC and the offset to apply to get the linked
1100 /// address.
1101 ///
1102 /// See startDebugObject() for a more complete description of its use.
1103 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Rissd3455182015-01-28 18:27:01 +00001104};
1105
Frederic Riss1b9da422015-02-13 23:18:29 +00001106/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1107/// returning our CompileUnit object instead.
1108CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1109 auto CU =
1110 std::upper_bound(Units.begin(), Units.end(), Offset,
1111 [](uint32_t LHS, const CompileUnit &RHS) {
1112 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1113 });
1114 return CU != Units.end() ? &*CU : nullptr;
1115}
1116
1117/// \brief Resolve the DIE attribute reference that has been
1118/// extracted in \p RefValue. The resulting DIE migh be in another
1119/// CompileUnit which is stored into \p ReferencedCU.
1120/// \returns null if resolving fails for any reason.
1121const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1122 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1123 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1124 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1125 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1126
1127 if ((RefCU = getUnitForOffset(RefOffset)))
1128 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1129 return RefDie;
1130
1131 reportWarning("could not find referenced DIE", &Unit, &DIE);
1132 return nullptr;
1133}
1134
1135/// \brief Report a warning to the user, optionaly including
1136/// information about a specific \p DIE related to the warning.
1137void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001138 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001139 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001140 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001141 Context = CurrentDebugObject->getObjectFilename();
1142 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001143
Frederic Rissb9818322015-02-28 00:29:07 +00001144 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001145 return;
1146
1147 errs() << " in DIE:\n";
1148 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1149 6 /* Indent */);
1150}
1151
Frederic Rissc99ea202015-02-28 00:29:11 +00001152bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1153 if (Options.NoOutput)
1154 return true;
1155
Frederic Rissb52cf522015-02-28 00:42:37 +00001156 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001157 return Streamer->init(TheTriple, OutputFilename);
1158}
1159
Frederic Riss563cba62015-01-28 22:15:14 +00001160/// \brief Recursive helper to gather the child->parent relationships in the
1161/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001162static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1163 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +00001164 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1165 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1166
1167 if (DIE->hasChildren())
1168 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1169 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +00001170 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +00001171}
1172
Frederic Riss84c09a52015-02-13 23:18:34 +00001173static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1174 switch (Tag) {
1175 default:
1176 return false;
1177 case dwarf::DW_TAG_subprogram:
1178 case dwarf::DW_TAG_lexical_block:
1179 case dwarf::DW_TAG_subroutine_type:
1180 case dwarf::DW_TAG_structure_type:
1181 case dwarf::DW_TAG_class_type:
1182 case dwarf::DW_TAG_union_type:
1183 return true;
1184 }
1185 llvm_unreachable("Invalid Tag");
1186}
1187
Frederic Riss63786b02015-03-15 20:45:43 +00001188void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001189 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001190 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001191 // Iterate over the debug map entries and put all the ones that are
1192 // functions (because they have a size) into the Ranges map. This
1193 // map is very similar to the FunctionRanges that are stored in each
1194 // unit, with 2 notable differences:
1195 // - obviously this one is global, while the other ones are per-unit.
1196 // - this one contains not only the functions described in the DIE
1197 // tree, but also the ones that are only in the debug map.
1198 // The latter information is required to reproduce dsymutil's logic
1199 // while linking line tables. The cases where this information
1200 // matters look like bugs that need to be investigated, but for now
1201 // we need to reproduce dsymutil's behavior.
1202 // FIXME: Once we understood exactly if that information is needed,
1203 // maybe totally remove this (or try to use it to do a real
1204 // -gline-tables-only on Darwin.
1205 for (const auto &Entry : Obj.symbols()) {
1206 const auto &Mapping = Entry.getValue();
1207 if (Mapping.Size)
1208 Ranges[Mapping.ObjectAddress] = std::make_pair(
1209 Mapping.ObjectAddress + Mapping.Size,
1210 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1211 }
Frederic Riss563cba62015-01-28 22:15:14 +00001212}
1213
Frederic Riss1036e642015-02-13 23:18:22 +00001214void DwarfLinker::endDebugObject() {
1215 Units.clear();
1216 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001217 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001218
1219 for (auto *Block : DIEBlocks)
1220 Block->~DIEBlock();
1221 for (auto *Loc : DIELocs)
1222 Loc->~DIELoc();
1223
1224 DIEBlocks.clear();
1225 DIELocs.clear();
1226 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001227}
1228
1229/// \brief Iterate over the relocations of the given \p Section and
1230/// store the ones that correspond to debug map entries into the
1231/// ValidRelocs array.
1232void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1233 const object::MachOObjectFile &Obj,
1234 const DebugMapObject &DMO) {
1235 StringRef Contents;
1236 Section.getContents(Contents);
1237 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1238
1239 for (const object::RelocationRef &Reloc : Section.relocations()) {
1240 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1241 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1242 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1243 uint64_t Offset64;
1244 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001245 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001246 continue;
1247 }
1248 uint32_t Offset = Offset64;
1249 // Mach-o uses REL relocations, the addend is at the relocation offset.
1250 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1251
1252 auto Sym = Reloc.getSymbol();
1253 if (Sym != Obj.symbol_end()) {
1254 StringRef SymbolName;
1255 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001256 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001257 continue;
1258 }
1259 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1260 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1261 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1262 // Do not store the addend. The addend was the address of the
1263 // symbol in the object file, the address in the binary that is
1264 // stored in the debug map doesn't need to be offseted.
1265 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1266 }
1267 }
1268}
1269
1270/// \brief Dispatch the valid relocation finding logic to the
1271/// appropriate handler depending on the object file format.
1272bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1273 const object::ObjectFile &Obj,
1274 const DebugMapObject &DMO) {
1275 // Dispatch to the right handler depending on the file type.
1276 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1277 findValidRelocsMachO(Section, *MachOObj, DMO);
1278 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001279 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001280
1281 if (ValidRelocs.empty())
1282 return false;
1283
1284 // Sort the relocations by offset. We will walk the DIEs linearly in
1285 // the file, this allows us to just keep an index in the relocation
1286 // array that we advance during our walk, rather than resorting to
1287 // some associative container. See DwarfLinker::NextValidReloc.
1288 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1289 return true;
1290}
1291
1292/// \brief Look for relocations in the debug_info section that match
1293/// entries in the debug map. These relocations will drive the Dwarf
1294/// link by indicating which DIEs refer to symbols present in the
1295/// linked binary.
1296/// \returns wether there are any valid relocations in the debug info.
1297bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1298 const DebugMapObject &DMO) {
1299 // Find the debug_info section.
1300 for (const object::SectionRef &Section : Obj.sections()) {
1301 StringRef SectionName;
1302 Section.getName(SectionName);
1303 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1304 if (SectionName != "debug_info")
1305 continue;
1306 return findValidRelocs(Section, Obj, DMO);
1307 }
1308 return false;
1309}
Frederic Riss563cba62015-01-28 22:15:14 +00001310
Frederic Riss84c09a52015-02-13 23:18:34 +00001311/// \brief Checks that there is a relocation against an actual debug
1312/// map entry between \p StartOffset and \p NextOffset.
1313///
1314/// This function must be called with offsets in strictly ascending
1315/// order because it never looks back at relocations it already 'went past'.
1316/// \returns true and sets Info.InDebugMap if it is the case.
1317bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1318 CompileUnit::DIEInfo &Info) {
1319 assert(NextValidReloc == 0 ||
1320 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1321 if (NextValidReloc >= ValidRelocs.size())
1322 return false;
1323
1324 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1325
1326 // We might need to skip some relocs that we didn't consider. For
1327 // example the high_pc of a discarded DIE might contain a reloc that
1328 // is in the list because it actually corresponds to the start of a
1329 // function that is in the debug map.
1330 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1331 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1332
1333 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1334 return false;
1335
1336 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +00001337 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001338 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1339 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1340 ValidReloc.Mapping->getValue().ObjectAddress,
1341 ValidReloc.Mapping->getValue().BinaryAddress);
1342
Frederic Riss31da3242015-03-11 18:45:52 +00001343 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1344 ValidReloc.Addend -
1345 ValidReloc.Mapping->getValue().ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001346 Info.InDebugMap = true;
1347 return true;
1348}
1349
1350/// \brief Get the starting and ending (exclusive) offset for the
1351/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1352/// supposed to point to the position of the first attribute described
1353/// by \p Abbrev.
1354/// \return [StartOffset, EndOffset) as a pair.
1355static std::pair<uint32_t, uint32_t>
1356getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1357 unsigned Offset, const DWARFUnit &Unit) {
1358 DataExtractor Data = Unit.getDebugInfoExtractor();
1359
1360 for (unsigned i = 0; i < Idx; ++i)
1361 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1362
1363 uint32_t End = Offset;
1364 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1365
1366 return std::make_pair(Offset, End);
1367}
1368
1369/// \brief Check if a variable describing DIE should be kept.
1370/// \returns updated TraversalFlags.
1371unsigned DwarfLinker::shouldKeepVariableDIE(
1372 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1373 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1374 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1375
1376 // Global variables with constant value can always be kept.
1377 if (!(Flags & TF_InFunctionScope) &&
1378 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1379 MyInfo.InDebugMap = true;
1380 return Flags | TF_Keep;
1381 }
1382
1383 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1384 if (LocationIdx == -1U)
1385 return Flags;
1386
1387 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1388 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1389 uint32_t LocationOffset, LocationEndOffset;
1390 std::tie(LocationOffset, LocationEndOffset) =
1391 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1392
1393 // See if there is a relocation to a valid debug map entry inside
1394 // this variable's location. The order is important here. We want to
1395 // always check in the variable has a valid relocation, so that the
1396 // DIEInfo is filled. However, we don't want a static variable in a
1397 // function to force us to keep the enclosing function.
1398 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1399 (Flags & TF_InFunctionScope))
1400 return Flags;
1401
Frederic Rissb9818322015-02-28 00:29:07 +00001402 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001403 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1404
1405 return Flags | TF_Keep;
1406}
1407
1408/// \brief Check if a function describing DIE should be kept.
1409/// \returns updated TraversalFlags.
1410unsigned DwarfLinker::shouldKeepSubprogramDIE(
1411 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1412 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1413 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1414
1415 Flags |= TF_InFunctionScope;
1416
1417 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1418 if (LowPcIdx == -1U)
1419 return Flags;
1420
1421 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1422 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1423 uint32_t LowPcOffset, LowPcEndOffset;
1424 std::tie(LowPcOffset, LowPcEndOffset) =
1425 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1426
1427 uint64_t LowPc =
1428 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1429 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1430 if (LowPc == -1ULL ||
1431 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1432 return Flags;
1433
Frederic Rissb9818322015-02-28 00:29:07 +00001434 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001435 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1436
Frederic Riss1af75f72015-03-12 18:45:10 +00001437 Flags |= TF_Keep;
1438
1439 DWARFFormValue HighPcValue;
1440 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1441 reportWarning("Function without high_pc. Range will be discarded.\n",
1442 &OrigUnit, &DIE);
1443 return Flags;
1444 }
1445
1446 uint64_t HighPc;
1447 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1448 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1449 } else {
1450 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1451 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1452 }
1453
Frederic Riss63786b02015-03-15 20:45:43 +00001454 // Replace the debug map range with a more accurate one.
1455 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001456 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1457 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001458}
1459
1460/// \brief Check if a DIE should be kept.
1461/// \returns updated TraversalFlags.
1462unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1463 CompileUnit &Unit,
1464 CompileUnit::DIEInfo &MyInfo,
1465 unsigned Flags) {
1466 switch (DIE.getTag()) {
1467 case dwarf::DW_TAG_constant:
1468 case dwarf::DW_TAG_variable:
1469 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1470 case dwarf::DW_TAG_subprogram:
1471 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1472 case dwarf::DW_TAG_module:
1473 case dwarf::DW_TAG_imported_module:
1474 case dwarf::DW_TAG_imported_declaration:
1475 case dwarf::DW_TAG_imported_unit:
1476 // We always want to keep these.
1477 return Flags | TF_Keep;
1478 }
1479
1480 return Flags;
1481}
1482
Frederic Riss84c09a52015-02-13 23:18:34 +00001483/// \brief Mark the passed DIE as well as all the ones it depends on
1484/// as kept.
1485///
1486/// This function is called by lookForDIEsToKeep on DIEs that are
1487/// newly discovered to be needed in the link. It recursively calls
1488/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1489/// TraversalFlags to inform it that it's not doing the primary DIE
1490/// tree walk.
1491void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1492 CompileUnit::DIEInfo &MyInfo,
1493 const DebugMapObject &DMO,
1494 CompileUnit &CU, unsigned Flags) {
1495 const DWARFUnit &Unit = CU.getOrigUnit();
1496 MyInfo.Keep = true;
1497
1498 // First mark all the parent chain as kept.
1499 unsigned AncestorIdx = MyInfo.ParentIdx;
1500 while (!CU.getInfo(AncestorIdx).Keep) {
1501 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1502 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1503 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1504 }
1505
1506 // Then we need to mark all the DIEs referenced by this DIE's
1507 // attributes as kept.
1508 DataExtractor Data = Unit.getDebugInfoExtractor();
1509 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1510 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1511
1512 // Mark all DIEs referenced through atttributes as kept.
1513 for (const auto &AttrSpec : Abbrev->attributes()) {
1514 DWARFFormValue Val(AttrSpec.Form);
1515
1516 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1517 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1518 continue;
1519 }
1520
1521 Val.extractValue(Data, &Offset, &Unit);
1522 CompileUnit *ReferencedCU;
1523 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1524 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1525 TF_Keep | TF_DependencyWalk);
1526 }
1527}
1528
1529/// \brief Recursively walk the \p DIE tree and look for DIEs to
1530/// keep. Store that information in \p CU's DIEInfo.
1531///
1532/// This function is the entry point of the DIE selection
1533/// algorithm. It is expected to walk the DIE tree in file order and
1534/// (though the mediation of its helper) call hasValidRelocation() on
1535/// each DIE that might be a 'root DIE' (See DwarfLinker class
1536/// comment).
1537/// While walking the dependencies of root DIEs, this function is
1538/// also called, but during these dependency walks the file order is
1539/// not respected. The TF_DependencyWalk flag tells us which kind of
1540/// traversal we are currently doing.
1541void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1542 const DebugMapObject &DMO, CompileUnit &CU,
1543 unsigned Flags) {
1544 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1545 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1546 bool AlreadyKept = MyInfo.Keep;
1547
1548 // If the Keep flag is set, we are marking a required DIE's
1549 // dependencies. If our target is already marked as kept, we're all
1550 // set.
1551 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1552 return;
1553
1554 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1555 // because it would screw up the relocation finding logic.
1556 if (!(Flags & TF_DependencyWalk))
1557 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1558
1559 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1560 if (!AlreadyKept && (Flags & TF_Keep))
1561 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1562
1563 // The TF_ParentWalk flag tells us that we are currently walking up
1564 // the parent chain of a required DIE, and we don't want to mark all
1565 // the children of the parents as kept (consider for example a
1566 // DW_TAG_namespace node in the parent chain). There are however a
1567 // set of DIE types for which we want to ignore that directive and still
1568 // walk their children.
1569 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1570 Flags &= ~TF_ParentWalk;
1571
1572 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1573 return;
1574
1575 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1576 Child = Child->getSibling())
1577 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1578}
1579
Frederic Rissb8b43d52015-03-04 22:07:44 +00001580/// \brief Assign an abbreviation numer to \p Abbrev.
1581///
1582/// Our DIEs get freed after every DebugMapObject has been processed,
1583/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1584/// the instances hold by the DIEs. When we encounter an abbreviation
1585/// that we don't know, we create a permanent copy of it.
1586void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1587 // Check the set for priors.
1588 FoldingSetNodeID ID;
1589 Abbrev.Profile(ID);
1590 void *InsertToken;
1591 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1592
1593 // If it's newly added.
1594 if (InSet) {
1595 // Assign existing abbreviation number.
1596 Abbrev.setNumber(InSet->getNumber());
1597 } else {
1598 // Add to abbreviation list.
1599 Abbreviations.push_back(
1600 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1601 for (const auto &Attr : Abbrev.getData())
1602 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1603 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1604 // Assign the unique abbreviation number.
1605 Abbrev.setNumber(Abbreviations.size());
1606 Abbreviations.back()->setNumber(Abbreviations.size());
1607 }
1608}
1609
1610/// \brief Clone a string attribute described by \p AttrSpec and add
1611/// it to \p Die.
1612/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001613unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1614 const DWARFFormValue &Val,
1615 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001616 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001617 const char *String = *Val.getAsCString(&U);
1618 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001619 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Frederic Rissef648462015-03-06 17:56:30 +00001620 new (DIEAlloc) DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001621 return 4;
1622}
1623
1624/// \brief Clone an attribute referencing another DIE and add
1625/// it to \p Die.
1626/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001627unsigned DwarfLinker::cloneDieReferenceAttribute(
1628 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1629 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001630 CompileUnit &Unit) {
1631 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
Frederic Riss9833de62015-03-06 23:22:53 +00001632 DIE *NewRefDie = nullptr;
1633 CompileUnit *RefUnit = nullptr;
1634 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1635
1636 if (!(RefUnit = getUnitForOffset(Ref)) ||
1637 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1638 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1639 if (!AttributeString)
1640 AttributeString = "DW_AT_???";
1641 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1642 ". Dropping.",
Frederic Riss6afcfce2015-03-13 18:35:57 +00001643 &Unit.getOrigUnit(), &InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001644 return 0;
1645 }
1646
1647 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1648 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1649 if (!RefInfo.Clone) {
1650 assert(Ref > InputDIE.getOffset());
1651 // We haven't cloned this DIE yet. Just create an empty one and
1652 // store it. It'll get really cloned when we process it.
1653 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1654 }
1655 NewRefDie = RefInfo.Clone;
1656
1657 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1658 // We cannot currently rely on a DIEEntry to emit ref_addr
1659 // references, because the implementation calls back to DwarfDebug
1660 // to find the unit offset. (We don't have a DwarfDebug)
1661 // FIXME: we should be able to design DIEEntry reliance on
1662 // DwarfDebug away.
1663 DIEInteger *Attr;
1664 if (Ref < InputDIE.getOffset()) {
1665 // We must have already cloned that DIE.
1666 uint32_t NewRefOffset =
1667 RefUnit->getStartOffset() + NewRefDie->getOffset();
1668 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1669 } else {
1670 // A forward reference. Note and fixup later.
1671 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
Frederic Riss6afcfce2015-03-13 18:35:57 +00001672 Unit.noteForwardReference(NewRefDie, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +00001673 }
1674 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1675 Attr);
1676 return AttrSize;
1677 }
1678
Frederic Rissb8b43d52015-03-04 22:07:44 +00001679 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss9833de62015-03-06 23:22:53 +00001680 new (DIEAlloc) DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001681 return AttrSize;
1682}
1683
1684/// \brief Clone an attribute of block form (locations, constants) and add
1685/// it to \p Die.
1686/// \returns the size of the new attribute.
1687unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1688 const DWARFFormValue &Val,
1689 unsigned AttrSize) {
1690 DIE *Attr;
1691 DIEValue *Value;
1692 DIELoc *Loc = nullptr;
1693 DIEBlock *Block = nullptr;
1694 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001695 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001696 Loc = new (DIEAlloc) DIELoc();
1697 DIELocs.push_back(Loc);
1698 } else {
1699 Block = new (DIEAlloc) DIEBlock();
1700 DIEBlocks.push_back(Block);
1701 }
1702 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1703 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1704 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1705 for (auto Byte : Bytes)
1706 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1707 new (DIEAlloc) DIEInteger(Byte));
1708 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1709 // the DIE class, this if could be replaced by
1710 // Attr->setSize(Bytes.size()).
1711 if (Streamer) {
1712 if (Loc)
1713 Loc->ComputeSize(&Streamer->getAsmPrinter());
1714 else
1715 Block->ComputeSize(&Streamer->getAsmPrinter());
1716 }
1717 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1718 Value);
1719 return AttrSize;
1720}
1721
Frederic Riss31da3242015-03-11 18:45:52 +00001722/// \brief Clone an address attribute and add it to \p Die.
1723/// \returns the size of the new attribute.
1724unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1725 const DWARFFormValue &Val,
1726 const CompileUnit &Unit,
1727 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001728 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00001729 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1730 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1731 Die.getTag() == dwarf::DW_TAG_lexical_block)
1732 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001733 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1734 Addr = Unit.getLowPc();
1735 if (Addr == UINT64_MAX)
1736 return 0;
1737 }
Frederic Riss31da3242015-03-11 18:45:52 +00001738 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001739 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1740 if (uint64_t HighPc = Unit.getHighPc())
1741 Addr = HighPc;
1742 else
1743 return 0;
1744 } else
1745 // If we have a high_pc recorded for the input DIE, use
1746 // it. Otherwise (when no relocations where applied) just use the
1747 // one we just decoded.
1748 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00001749 }
1750
1751 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1752 static_cast<dwarf::Form>(AttrSpec.Form),
1753 new (DIEAlloc) DIEInteger(Addr));
1754 return Unit.getOrigUnit().getAddressByteSize();
1755}
1756
Frederic Rissb8b43d52015-03-04 22:07:44 +00001757/// \brief Clone a scalar attribute and add it to \p Die.
1758/// \returns the size of the new attribute.
1759unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00001760 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00001761 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
1762 const AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001763 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001764 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1765 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1766 if (Unit.getLowPc() == -1ULL)
1767 return 0;
1768 // Dwarf >= 4 high_pc is an size, not an address.
1769 Value = Unit.getHighPc() - Unit.getLowPc();
1770 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00001771 Value = *Val.getAsSectionOffset();
1772 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1773 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001774 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1775 Value = *OptionalValue;
1776 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001777 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1778 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001779 return 0;
1780 }
Frederic Riss25440872015-03-13 23:30:31 +00001781 DIEInteger *Attr = new (DIEAlloc) DIEInteger(Value);
1782 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
1783 Unit.noteRangeAttribute(Die, Attr);
Frederic Rissdfb97902015-03-14 15:49:07 +00001784 // A more generic way to check for location attributes would be
1785 // nice, but it's very unlikely that any other attribute needs a
1786 // location list.
1787 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1788 AttrSpec.Attr == dwarf::DW_AT_frame_base)
1789 Unit.noteLocationAttribute(Attr, Info.PCOffset);
1790
Frederic Rissb8b43d52015-03-04 22:07:44 +00001791 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss25440872015-03-13 23:30:31 +00001792 Attr);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001793 return AttrSize;
1794}
1795
1796/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1797/// value \p Val, and add it to \p Die.
1798/// \returns the size of the cloned attribute.
1799unsigned DwarfLinker::cloneAttribute(DIE &Die,
1800 const DWARFDebugInfoEntryMinimal &InputDIE,
1801 CompileUnit &Unit,
1802 const DWARFFormValue &Val,
1803 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00001804 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001805 const DWARFUnit &U = Unit.getOrigUnit();
1806
1807 switch (AttrSpec.Form) {
1808 case dwarf::DW_FORM_strp:
1809 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00001810 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001811 case dwarf::DW_FORM_ref_addr:
1812 case dwarf::DW_FORM_ref1:
1813 case dwarf::DW_FORM_ref2:
1814 case dwarf::DW_FORM_ref4:
1815 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00001816 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001817 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001818 case dwarf::DW_FORM_block:
1819 case dwarf::DW_FORM_block1:
1820 case dwarf::DW_FORM_block2:
1821 case dwarf::DW_FORM_block4:
1822 case dwarf::DW_FORM_exprloc:
1823 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1824 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00001825 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001826 case dwarf::DW_FORM_data1:
1827 case dwarf::DW_FORM_data2:
1828 case dwarf::DW_FORM_data4:
1829 case dwarf::DW_FORM_data8:
1830 case dwarf::DW_FORM_udata:
1831 case dwarf::DW_FORM_sdata:
1832 case dwarf::DW_FORM_sec_offset:
1833 case dwarf::DW_FORM_flag:
1834 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00001835 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
1836 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001837 default:
1838 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1839 &InputDIE);
1840 }
1841
1842 return 0;
1843}
1844
Frederic Riss23e20e92015-03-07 01:25:09 +00001845/// \brief Apply the valid relocations found by findValidRelocs() to
1846/// the buffer \p Data, taking into account that Data is at \p BaseOffset
1847/// in the debug_info section.
1848///
1849/// Like for findValidRelocs(), this function must be called with
1850/// monotonic \p BaseOffset values.
1851///
1852/// \returns wether any reloc has been applied.
1853bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1854 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00001855 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00001856 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1857 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00001858 if (NextValidReloc >= ValidRelocs.size())
1859 return false;
1860
1861 // Skip relocs that haven't been applied.
1862 while (NextValidReloc < ValidRelocs.size() &&
1863 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1864 ++NextValidReloc;
1865
1866 bool Applied = false;
1867 uint64_t EndOffset = BaseOffset + Data.size();
1868 while (NextValidReloc < ValidRelocs.size() &&
1869 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1870 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1871 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1872 assert(ValidReloc.Offset - BaseOffset < Data.size());
1873 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1874 char Buf[8];
1875 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1876 Value += ValidReloc.Addend;
1877 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1878 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1879 Buf[i] = uint8_t(Value >> (Index * 8));
1880 }
1881 assert(ValidReloc.Size <= sizeof(Buf));
1882 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1883 Applied = true;
1884 }
1885
1886 return Applied;
1887}
1888
Frederic Rissb8b43d52015-03-04 22:07:44 +00001889/// \brief Recursively clone \p InputDIE's subtrees that have been
1890/// selected to appear in the linked output.
1891///
1892/// \param OutOffset is the Offset where the newly created DIE will
1893/// lie in the linked compile unit.
1894///
1895/// \returns the cloned DIE object or null if nothing was selected.
1896DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00001897 CompileUnit &Unit, int64_t PCOffset,
1898 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001899 DWARFUnit &U = Unit.getOrigUnit();
1900 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001901 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001902
1903 // Should the DIE appear in the output?
1904 if (!Unit.getInfo(Idx).Keep)
1905 return nullptr;
1906
1907 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00001908 // The DIE might have been already created by a forward reference
1909 // (see cloneDieReferenceAttribute()).
1910 DIE *Die = Info.Clone;
1911 if (!Die)
1912 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1913 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00001914 Die->setOffset(OutOffset);
1915
1916 // Extract and clone every attribute.
1917 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00001918 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00001919 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00001920
1921 // We could copy the data only if we need to aply a relocation to
1922 // it. After testing, it seems there is no performance downside to
1923 // doing the copy unconditionally, and it makes the code simpler.
1924 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1925 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1926 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00001927 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1928 // If we applied relocations, we store the value of high_pc that was
1929 // potentially stored in the input DIE. If high_pc is an address
1930 // (Dwarf version == 2), then it might have been relocated to a
1931 // totally unrelated value (because the end address in the object
1932 // file might be start address of another function which got moved
1933 // independantly by the linker). The computation of the actual
1934 // high_pc value is done in cloneAddressAttribute().
1935 AttrInfo.OrigHighPc =
1936 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
1937 }
Frederic Riss23e20e92015-03-07 01:25:09 +00001938
1939 // Reset the Offset to 0 as we will be working on the local copy of
1940 // the data.
1941 Offset = 0;
1942
Frederic Rissb8b43d52015-03-04 22:07:44 +00001943 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1944 Offset += getULEB128Size(Abbrev->getCode());
1945
Frederic Riss31da3242015-03-11 18:45:52 +00001946 // We are entering a subprogram. Get and propagate the PCOffset.
1947 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1948 PCOffset = Info.AddrAdjust;
1949 AttrInfo.PCOffset = PCOffset;
1950
Frederic Rissb8b43d52015-03-04 22:07:44 +00001951 for (const auto &AttrSpec : Abbrev->attributes()) {
1952 DWARFFormValue Val(AttrSpec.Form);
1953 uint32_t AttrSize = Offset;
1954 Val.extractValue(Data, &Offset, &U);
1955 AttrSize = Offset - AttrSize;
1956
Frederic Riss31da3242015-03-11 18:45:52 +00001957 OutOffset +=
1958 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001959 }
1960
1961 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1962 // If a scope DIE is kept, we must have kept at least one child. If
1963 // it's not the case, we'll just be emitting one wasteful end of
1964 // children marker, but things won't break.
1965 if (InputDIE.hasChildren())
1966 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1967 // Assign a permanent abbrev number
1968 AssignAbbrev(Die->getAbbrev());
1969
1970 // Add the size of the abbreviation number to the output offset.
1971 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1972
1973 if (!Abbrev->hasChildren()) {
1974 // Update our size.
1975 Die->setSize(OutOffset - Die->getOffset());
1976 return Die;
1977 }
1978
1979 // Recursively clone children.
1980 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1981 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00001982 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001983 Die->addChild(std::unique_ptr<DIE>(Clone));
1984 OutOffset = Clone->getOffset() + Clone->getSize();
1985 }
1986 }
1987
1988 // Account for the end of children marker.
1989 OutOffset += sizeof(int8_t);
1990 // Update our size.
1991 Die->setSize(OutOffset - Die->getOffset());
1992 return Die;
1993}
1994
Frederic Riss25440872015-03-13 23:30:31 +00001995/// \brief Patch the input object file relevant debug_ranges entries
1996/// and emit them in the output file. Update the relevant attributes
1997/// to point at the new entries.
1998void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
1999 DWARFContext &OrigDwarf) const {
2000 DWARFDebugRangeList RangeList;
2001 const auto &FunctionRanges = Unit.getFunctionRanges();
2002 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2003 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2004 OrigDwarf.isLittleEndian(), AddressSize);
2005 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2006 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2007 const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
2008 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2009 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2010 // Ranges addresses are based on the unit's low_pc. Compute the
2011 // offset we need to apply to adapt to the the new unit's low_pc.
2012 int64_t UnitPcOffset = 0;
2013 if (OrigLowPc != -1ULL)
2014 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2015
2016 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2017 uint32_t Offset = RangeAttribute->getValue();
2018 RangeAttribute->setValue(Streamer->getRangesSectionSize());
2019 RangeList.extract(RangeExtractor, &Offset);
2020 const auto &Entries = RangeList.getEntries();
2021 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2022
2023 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2024 First.StartAddress >= CurrRange.stop()) {
2025 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2026 if (CurrRange == InvalidRange ||
2027 CurrRange.start() > First.StartAddress + OrigLowPc) {
2028 reportWarning("no mapping for range.");
2029 continue;
2030 }
2031 }
2032
2033 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2034 AddressSize);
2035 }
2036}
2037
Frederic Riss563b1b02015-03-14 03:46:51 +00002038/// \brief Generate the debug_aranges entries for \p Unit and if the
2039/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2040/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002041/// FIXME: this could actually be done right in patchRangesForUnit,
2042/// but for the sake of initial bit-for-bit compatibility with legacy
2043/// dsymutil, we have to do it in a delayed pass.
2044void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Frederic Riss563b1b02015-03-14 03:46:51 +00002045 DIEInteger *Attr = Unit.getUnitRangesAttribute();
2046 if (Attr)
Frederic Riss25440872015-03-13 23:30:31 +00002047 Attr->setValue(Streamer->getRangesSectionSize());
Frederic Riss563b1b02015-03-14 03:46:51 +00002048 Streamer->emitUnitRangesEntries(Unit, Attr != nullptr);
Frederic Riss25440872015-03-13 23:30:31 +00002049}
2050
Frederic Riss63786b02015-03-15 20:45:43 +00002051/// \brief Insert the new line info sequence \p Seq into the current
2052/// set of already linked line info \p Rows.
2053static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2054 std::vector<DWARFDebugLine::Row> &Rows) {
2055 if (Seq.empty())
2056 return;
2057
2058 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2059 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2060 Seq.clear();
2061 return;
2062 }
2063
2064 auto InsertPoint = std::lower_bound(
2065 Rows.begin(), Rows.end(), Seq.front(),
2066 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2067 return LHS.Address < RHS.Address;
2068 });
2069
2070 // FIXME: this only removes the unneeded end_sequence if the
2071 // sequences have been inserted in order. using a global sort like
2072 // described in patchLineTableForUnit() and delaying the end_sequene
2073 // elimination to emitLineTableForUnit() we can get rid of all of them.
2074 if (InsertPoint != Rows.end() &&
2075 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2076 *InsertPoint = Seq.front();
2077 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2078 } else {
2079 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2080 }
2081
2082 Seq.clear();
2083}
2084
2085/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2086/// recreate a relocated version of these for the address ranges that
2087/// are present in the binary.
2088void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2089 DWARFContext &OrigDwarf) {
2090 const DWARFDebugInfoEntryMinimal *CUDie =
2091 Unit.getOrigUnit().getCompileUnitDIE();
2092 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2093 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2094 if (StmtList == -1ULL)
2095 return;
2096
2097 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2098 if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
2099 const auto &Abbrev = OutputDIE->getAbbrev().getData();
2100 auto Stmt = std::find_if(
2101 Abbrev.begin(), Abbrev.end(), [](const DIEAbbrevData &AbbrevData) {
2102 return AbbrevData.getAttribute() == dwarf::DW_AT_stmt_list;
2103 });
2104 assert(Stmt < Abbrev.end() && "Didn't find DW_AT_stmt_list in cloned DIE!");
2105 DIEInteger *StmtAttr =
2106 cast<DIEInteger>(OutputDIE->getValues()[Stmt - Abbrev.begin()]);
2107 StmtAttr->setValue(Streamer->getLineSectionSize());
2108 }
2109
2110 // Parse the original line info for the unit.
2111 DWARFDebugLine::LineTable LineTable;
2112 uint32_t StmtOffset = StmtList;
2113 StringRef LineData = OrigDwarf.getLineSection().Data;
2114 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2115 Unit.getOrigUnit().getAddressByteSize());
2116 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2117 &StmtOffset);
2118
2119 // This vector is the output line table.
2120 std::vector<DWARFDebugLine::Row> NewRows;
2121 NewRows.reserve(LineTable.Rows.size());
2122
2123 // Current sequence of rows being extracted, before being inserted
2124 // in NewRows.
2125 std::vector<DWARFDebugLine::Row> Seq;
2126 const auto &FunctionRanges = Unit.getFunctionRanges();
2127 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2128
2129 // FIXME: This logic is meant to generate exactly the same output as
2130 // Darwin's classic dsynutil. There is a nicer way to implement this
2131 // by simply putting all the relocated line info in NewRows and simply
2132 // sorting NewRows before passing it to emitLineTableForUnit. This
2133 // should be correct as sequences for a function should stay
2134 // together in the sorted output. There are a few corner cases that
2135 // look suspicious though, and that required to implement the logic
2136 // this way. Revisit that once initial validation is finished.
2137
2138 // Iterate over the object file line info and extract the sequences
2139 // that correspond to linked functions.
2140 for (auto &Row : LineTable.Rows) {
2141 // Check wether we stepped out of the range. The range is
2142 // half-open, but consider accept the end address of the range if
2143 // it is marked as end_sequence in the input (because in that
2144 // case, the relocation offset is accurate and that entry won't
2145 // serve as the start of another function).
2146 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2147 Row.Address > CurrRange.stop() ||
2148 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2149 // We just stepped out of a known range. Insert a end_sequence
2150 // corresponding to the end of the range.
2151 uint64_t StopAddress = CurrRange != InvalidRange
2152 ? CurrRange.stop() + CurrRange.value()
2153 : -1ULL;
2154 CurrRange = FunctionRanges.find(Row.Address);
2155 bool CurrRangeValid =
2156 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2157 if (!CurrRangeValid) {
2158 CurrRange = InvalidRange;
2159 if (StopAddress != -1ULL) {
2160 // Try harder by looking in the DebugMapObject function
2161 // ranges map. There are corner cases where this finds a
2162 // valid entry. It's unclear if this is right or wrong, but
2163 // for now do as dsymutil.
2164 // FIXME: Understand exactly what cases this addresses and
2165 // potentially remove it along with the Ranges map.
2166 auto Range = Ranges.lower_bound(Row.Address);
2167 if (Range != Ranges.begin() && Range != Ranges.end())
2168 --Range;
2169
2170 if (Range != Ranges.end() && Range->first <= Row.Address &&
2171 Range->second.first >= Row.Address) {
2172 StopAddress = Row.Address + Range->second.second;
2173 }
2174 }
2175 }
2176 if (StopAddress != -1ULL && !Seq.empty()) {
2177 // Insert end sequence row with the computed end address, but
2178 // the same line as the previous one.
2179 Seq.emplace_back(Seq.back());
2180 Seq.back().Address = StopAddress;
2181 Seq.back().EndSequence = 1;
2182 Seq.back().PrologueEnd = 0;
2183 Seq.back().BasicBlock = 0;
2184 Seq.back().EpilogueBegin = 0;
2185 insertLineSequence(Seq, NewRows);
2186 }
2187
2188 if (!CurrRangeValid)
2189 continue;
2190 }
2191
2192 // Ignore empty sequences.
2193 if (Row.EndSequence && Seq.empty())
2194 continue;
2195
2196 // Relocate row address and add it to the current sequence.
2197 Row.Address += CurrRange.value();
2198 Seq.emplace_back(Row);
2199
2200 if (Row.EndSequence)
2201 insertLineSequence(Seq, NewRows);
2202 }
2203
2204 // Finished extracting, now emit the line tables.
2205 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2206 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2207 // prologue over and that works because we act as both producer and
2208 // consumer. It would be nicer to have a real configurable line
2209 // table emitter.
2210 if (LineTable.Prologue.Version != 2 ||
2211 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2212 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2213 LineTable.Prologue.OpcodeBase != 13)
2214 reportWarning("line table paramters mismatch. Cannot emit.");
2215 else
2216 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2217 LineTable.Prologue.MinInstLength, NewRows,
2218 Unit.getOrigUnit().getAddressByteSize());
2219}
2220
Frederic Rissd3455182015-01-28 18:27:01 +00002221bool DwarfLinker::link(const DebugMap &Map) {
2222
2223 if (Map.begin() == Map.end()) {
2224 errs() << "Empty debug map.\n";
2225 return false;
2226 }
2227
Frederic Rissc99ea202015-02-28 00:29:11 +00002228 if (!createStreamer(Map.getTriple(), OutputFilename))
2229 return false;
2230
Frederic Rissb8b43d52015-03-04 22:07:44 +00002231 // Size of the DIEs (and headers) generated for the linked output.
2232 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002233 // A unique ID that identifies each compile unit.
2234 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002235 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002236 CurrentDebugObject = Obj.get();
2237
Frederic Rissb9818322015-02-28 00:29:07 +00002238 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002239 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2240 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2241 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002242 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00002243 continue;
2244 }
2245
Frederic Riss1036e642015-02-13 23:18:22 +00002246 // Look for relocations that correspond to debug map entries.
2247 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002248 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002249 outs() << "No valid relocations found. Skipping.\n";
2250 continue;
2251 }
2252
Frederic Riss563cba62015-01-28 22:15:14 +00002253 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002254 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002255 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002256
Frederic Riss563cba62015-01-28 22:15:14 +00002257 // In a first phase, just read in the debug info and store the DIE
2258 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002259 for (const auto &CU : DwarfContext.compile_units()) {
2260 auto *CUDie = CU->getCompileUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002261 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002262 outs() << "Input compilation unit:";
2263 CUDie->dump(outs(), CU.get(), 0);
2264 }
Frederic Riss3cced052015-03-14 03:46:40 +00002265 Units.emplace_back(*CU, UnitID++);
Frederic Riss9aa725b2015-02-13 23:18:31 +00002266 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00002267 }
Frederic Riss563cba62015-01-28 22:15:14 +00002268
Frederic Riss84c09a52015-02-13 23:18:34 +00002269 // Then mark all the DIEs that need to be present in the linked
2270 // output and collect some information about them. Note that this
2271 // loop can not be merged with the previous one becaue cross-cu
2272 // references require the ParentIdx to be setup for every CU in
2273 // the object file before calling this.
2274 for (auto &CurrentUnit : Units)
2275 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
2276 CurrentUnit, 0);
2277
Frederic Riss23e20e92015-03-07 01:25:09 +00002278 // The calls to applyValidRelocs inside cloneDIE will walk the
2279 // reloc array again (in the same way findValidRelocsInDebugInfo()
2280 // did). We need to reset the NextValidReloc index to the beginning.
2281 NextValidReloc = 0;
2282
Frederic Rissb8b43d52015-03-04 22:07:44 +00002283 // Construct the output DIE tree by cloning the DIEs we chose to
2284 // keep above. If there are no valid relocs, then there's nothing
2285 // to clone/emit.
2286 if (!ValidRelocs.empty())
2287 for (auto &CurrentUnit : Units) {
2288 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00002289 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00002290 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2291 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002292 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00002293 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00002294 if (Options.NoOutput)
2295 continue;
2296 // FIXME: for compatibility with the classic dsymutil, we emit
2297 // an empty line table for the unit, even if the unit doesn't
2298 // actually exist in the DIE tree.
2299 patchLineTableForUnit(CurrentUnit, DwarfContext);
2300 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00002301 continue;
2302 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00002303 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002304 }
2305
2306 // Emit all the compile unit's debug information.
2307 if (!ValidRelocs.empty() && !Options.NoOutput)
2308 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00002309 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00002310 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002311 Streamer->emitCompileUnitHeader(CurrentUnit);
2312 if (!CurrentUnit.getOutputUnitDIE())
2313 continue;
2314 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2315 }
2316
Frederic Riss563cba62015-01-28 22:15:14 +00002317 // Clean-up before starting working on the next object.
2318 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00002319 }
2320
Frederic Rissb8b43d52015-03-04 22:07:44 +00002321 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00002322 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002323 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00002324 Streamer->emitStrings(StringPool);
2325 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002326
Frederic Rissc99ea202015-02-28 00:29:11 +00002327 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00002328}
2329}
Frederic Rissd3455182015-01-28 18:27:01 +00002330
Frederic Rissb9818322015-02-28 00:29:07 +00002331bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2332 const LinkOptions &Options) {
2333 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00002334 return Linker.link(DM);
2335}
2336}
Frederic Riss231f7142014-12-12 17:31:24 +00002337}