blob: c3fc92183d15cdff35c69c2c38c631266573e267 [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 Rissbce93ff2015-03-16 02:05:10 +0000146 /// \brief Add a name accelerator entry for \p Die with \p Name
147 /// which is stored in the string table at \p Offset.
148 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
149 bool SkipPubnamesSection = false);
150
151 /// \brief Add a type accelerator entry for \p Die with \p Name
152 /// which is stored in the string table at \p Offset.
153 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
154
155 struct AccelInfo {
156 StringRef Name; ///< Name of the entry.
157 const DIE *Die; ///< DIE this entry describes.
158 uint32_t NameOffset; ///< Offset of Name in the string pool.
159 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
160
161 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
162 bool SkipPubSection = false)
163 : Name(Name), Die(Die), NameOffset(NameOffset),
164 SkipPubSection(SkipPubSection) {}
165 };
166
167 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
168 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
169
Frederic Riss563cba62015-01-28 22:15:14 +0000170private:
171 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000172 unsigned ID;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000173 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
174 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
175
176 uint64_t StartOffset;
177 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000178
Frederic Riss5a62dc32015-03-13 18:35:54 +0000179 uint64_t LowPc;
180 uint64_t HighPc;
181
Frederic Riss9833de62015-03-06 23:22:53 +0000182 /// \brief A list of attributes to fixup with the absolute offset of
183 /// a DIE in the debug_info section.
184 ///
185 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000186 /// cloning because for cross-cu forward refences the target DIE's
187 /// offset isn't known you emit the reference attribute.
188 std::vector<std::tuple<DIE *, const CompileUnit *, DIEInteger *>>
189 ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000190
Frederic Riss25440872015-03-13 23:30:31 +0000191 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000192 /// \brief The ranges in that interval map are the PC ranges for
193 /// functions in this unit, associated with the PC offset to apply
194 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000195 FunctionIntervals Ranges;
196
197 /// \brief DW_AT_ranges attributes to patch after we have gathered
198 /// all the unit's function addresses.
199 /// @{
200 std::vector<DIEInteger *> RangeAttributes;
201 DIEInteger *UnitRangeAttribute;
202 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000203
204 /// \brief Location attributes that need to be transfered from th
205 /// original debug_loc section to the liked one. They are stored
206 /// along with the PC offset that is to be applied to their
207 /// function's address.
208 std::vector<std::pair<DIEInteger *, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000209
210 /// \brief Accelerator entries for the unit, both for the pub*
211 /// sections and the apple* ones.
212 /// @{
213 std::vector<AccelInfo> Pubnames;
214 std::vector<AccelInfo> Pubtypes;
215 /// @}
Frederic Riss563cba62015-01-28 22:15:14 +0000216};
217
Frederic Riss9d441b62015-03-06 23:22:50 +0000218uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000219 NextUnitOffset = StartOffset + 11 /* Header size */;
220 // The root DIE might be null, meaning that the Unit had nothing to
221 // contribute to the linked output. In that case, we will emit the
222 // unit header without any actual DIE.
223 if (CUDie)
224 NextUnitOffset += CUDie->getSize();
225 return NextUnitOffset;
226}
227
Frederic Riss6afcfce2015-03-13 18:35:57 +0000228/// \brief Keep track of a forward cross-cu reference from this unit
229/// to \p Die that lives in \p RefUnit.
230void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
231 DIEInteger *Attr) {
232 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000233}
234
235/// \brief Apply all fixups recorded by noteForwardReference().
236void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000237 for (const auto &Ref : ForwardDIEReferences) {
238 DIE *RefDie;
239 const CompileUnit *RefUnit;
240 DIEInteger *Attr;
241 std::tie(RefDie, RefUnit, Attr) = Ref;
242 Attr->setValue(RefDie->getOffset() + RefUnit->getStartOffset());
243 }
Frederic Riss9833de62015-03-06 23:22:53 +0000244}
245
Frederic Riss5a62dc32015-03-13 18:35:54 +0000246void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
247 int64_t PcOffset) {
248 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
249 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
250 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000251}
252
Frederic Riss25440872015-03-13 23:30:31 +0000253void CompileUnit::noteRangeAttribute(const DIE &Die, DIEInteger *Attr) {
254 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
255 RangeAttributes.push_back(Attr);
256 else
257 UnitRangeAttribute = Attr;
258}
259
Frederic Rissdfb97902015-03-14 15:49:07 +0000260void CompileUnit::noteLocationAttribute(DIEInteger *Attr, int64_t PcOffset) {
261 LocationAttributes.emplace_back(Attr, PcOffset);
262}
263
Frederic Rissbce93ff2015-03-16 02:05:10 +0000264/// \brief Add a name accelerator entry for \p Die with \p Name
265/// which is stored in the string table at \p Offset.
266void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
267 uint32_t Offset, bool SkipPubSection) {
268 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
269}
270
271/// \brief Add a type accelerator entry for \p Die with \p Name
272/// which is stored in the string table at \p Offset.
273void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
274 uint32_t Offset) {
275 Pubtypes.emplace_back(Name, Die, Offset, false);
276}
277
Frederic Rissef648462015-03-06 17:56:30 +0000278/// \brief A string table that doesn't need relocations.
279///
280/// We are doing a final link, no need for a string table that
281/// has relocation entries for every reference to it. This class
282/// provides this ablitity by just associating offsets with
283/// strings.
284class NonRelocatableStringpool {
285public:
286 /// \brief Entries are stored into the StringMap and simply linked
287 /// together through the second element of this pair in order to
288 /// keep track of insertion order.
289 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
290 MapTy;
291
292 NonRelocatableStringpool()
293 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
294 // Legacy dsymutil puts an empty string at the start of the line
295 // table.
296 getStringOffset("");
297 }
298
299 /// \brief Get the offset of string \p S in the string table. This
300 /// can insert a new element or return the offset of a preexisitng
301 /// one.
302 uint32_t getStringOffset(StringRef S);
303
304 /// \brief Get permanent storage for \p S (but do not necessarily
305 /// emit \p S in the output section).
306 /// \returns The StringRef that points to permanent storage to use
307 /// in place of \p S.
308 StringRef internString(StringRef S);
309
310 // \brief Return the first entry of the string table.
311 const MapTy::MapEntryTy *getFirstEntry() const {
312 return getNextEntry(&Sentinel);
313 }
314
315 // \brief Get the entry following \p E in the string table or null
316 // if \p E was the last entry.
317 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
318 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
319 }
320
321 uint64_t getSize() { return CurrentEndOffset; }
322
323private:
324 MapTy Strings;
325 uint32_t CurrentEndOffset;
326 MapTy::MapEntryTy Sentinel, *Last;
327};
328
329/// \brief Get the offset of string \p S in the string table. This
330/// can insert a new element or return the offset of a preexisitng
331/// one.
332uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
333 if (S.empty() && !Strings.empty())
334 return 0;
335
336 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
337 MapTy::iterator It;
338 bool Inserted;
339
340 // A non-empty string can't be at offset 0, so if we have an entry
341 // with a 0 offset, it must be a previously interned string.
342 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
343 if (Inserted || It->getValue().first == 0) {
344 // Set offset and chain at the end of the entries list.
345 It->getValue().first = CurrentEndOffset;
346 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
347 Last->getValue().second = &*It;
348 Last = &*It;
349 }
350 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000351}
Frederic Rissef648462015-03-06 17:56:30 +0000352
353/// \brief Put \p S into the StringMap so that it gets permanent
354/// storage, but do not actually link it in the chain of elements
355/// that go into the output section. A latter call to
356/// getStringOffset() with the same string will chain it though.
357StringRef NonRelocatableStringpool::internString(StringRef S) {
358 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
359 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
360 return InsertResult.first->getKey();
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000361}
Frederic Rissef648462015-03-06 17:56:30 +0000362
Frederic Rissc99ea202015-02-28 00:29:11 +0000363/// \brief The Dwarf streaming logic
364///
365/// All interactions with the MC layer that is used to build the debug
366/// information binary representation are handled in this class.
367class DwarfStreamer {
368 /// \defgroup MCObjects MC layer objects constructed by the streamer
369 /// @{
370 std::unique_ptr<MCRegisterInfo> MRI;
371 std::unique_ptr<MCAsmInfo> MAI;
372 std::unique_ptr<MCObjectFileInfo> MOFI;
373 std::unique_ptr<MCContext> MC;
374 MCAsmBackend *MAB; // Owned by MCStreamer
375 std::unique_ptr<MCInstrInfo> MII;
376 std::unique_ptr<MCSubtargetInfo> MSTI;
377 MCCodeEmitter *MCE; // Owned by MCStreamer
378 MCStreamer *MS; // Owned by AsmPrinter
379 std::unique_ptr<TargetMachine> TM;
380 std::unique_ptr<AsmPrinter> Asm;
381 /// @}
382
383 /// \brief the file we stream the linked Dwarf to.
384 std::unique_ptr<raw_fd_ostream> OutFile;
385
Frederic Riss25440872015-03-13 23:30:31 +0000386 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000387 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000388 uint32_t LineSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000389
Frederic Rissbce93ff2015-03-16 02:05:10 +0000390 /// \brief Emit the pubnames or pubtypes section contribution for \p
391 /// Unit into \p Sec. The data is provided in \p Names.
392 void emitPubSectionForUnit(const MCSection *Sec, StringRef Name,
393 const CompileUnit &Unit,
394 const std::vector<CompileUnit::AccelInfo> &Names);
395
Frederic Rissc99ea202015-02-28 00:29:11 +0000396public:
397 /// \brief Actually create the streamer and the ouptut file.
398 ///
399 /// This could be done directly in the constructor, but it feels
400 /// more natural to handle errors through return value.
401 bool init(Triple TheTriple, StringRef OutputFilename);
402
Frederic Rissb8b43d52015-03-04 22:07:44 +0000403 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000404 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000405
406 AsmPrinter &getAsmPrinter() const { return *Asm; }
407
408 /// \brief Set the current output section to debug_info and change
409 /// the MC Dwarf version to \p DwarfVersion.
410 void switchToDebugInfoSection(unsigned DwarfVersion);
411
412 /// \brief Emit the compilation unit header for \p Unit in the
413 /// debug_info section.
414 ///
415 /// As a side effect, this also switches the current Dwarf version
416 /// of the MC layer to the one of U.getOrigUnit().
417 void emitCompileUnitHeader(CompileUnit &Unit);
418
419 /// \brief Recursively emit the DIE tree rooted at \p Die.
420 void emitDIE(DIE &Die);
421
422 /// \brief Emit the abbreviation table \p Abbrevs to the
423 /// debug_abbrev section.
424 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000425
426 /// \brief Emit the string table described by \p Pool.
427 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000428
429 /// \brief Emit debug_ranges for \p FuncRange by translating the
430 /// original \p Entries.
431 void emitRangesEntries(
432 int64_t UnitPcOffset, uint64_t OrigLowPc,
433 FunctionIntervals::const_iterator FuncRange,
434 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
435 unsigned AddressSize);
436
Frederic Riss563b1b02015-03-14 03:46:51 +0000437 /// \brief Emit debug_aranges entries for \p Unit and if \p
438 /// DoRangesSection is true, also emit the debug_ranges entries for
439 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
440 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000441
442 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000443
444 /// \brief Emit the debug_loc contribution for \p Unit by copying
445 /// the entries from \p Dwarf and offseting them. Update the
446 /// location attributes to point to the new entries.
447 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000448
449 /// \brief Emit the line table described in \p Rows into the
450 /// debug_line section.
451 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
452 std::vector<DWARFDebugLine::Row> &Rows,
453 unsigned AdddressSize);
454
455 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000456
457 /// \brief Emit the .debug_pubnames contribution for \p Unit.
458 void emitPubNamesForUnit(const CompileUnit &Unit);
459
460 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
461 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Rissc99ea202015-02-28 00:29:11 +0000462};
463
464bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
465 std::string ErrorStr;
466 std::string TripleName;
467 StringRef Context = "dwarf streamer init";
468
469 // Get the target.
470 const Target *TheTarget =
471 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
472 if (!TheTarget)
473 return error(ErrorStr, Context);
474 TripleName = TheTriple.getTriple();
475
476 // Create all the MC Objects.
477 MRI.reset(TheTarget->createMCRegInfo(TripleName));
478 if (!MRI)
479 return error(Twine("no register info for target ") + TripleName, Context);
480
481 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
482 if (!MAI)
483 return error("no asm info for target " + TripleName, Context);
484
485 MOFI.reset(new MCObjectFileInfo);
486 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
487 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
488 *MC);
489
490 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
491 if (!MAB)
492 return error("no asm backend for target " + TripleName, Context);
493
494 MII.reset(TheTarget->createMCInstrInfo());
495 if (!MII)
496 return error("no instr info info for target " + TripleName, Context);
497
498 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
499 if (!MSTI)
500 return error("no subtarget info for target " + TripleName, Context);
501
Eric Christopher0169e422015-03-10 22:03:14 +0000502 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000503 if (!MCE)
504 return error("no code emitter for target " + TripleName, Context);
505
506 // Create the output file.
507 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000508 OutFile =
509 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000510 if (EC)
511 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
512
Rafael Espindolaf696df12015-03-16 22:29:29 +0000513 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Frederic Rissc99ea202015-02-28 00:29:11 +0000514 *MSTI, false);
515 if (!MS)
516 return error("no object streamer for target " + TripleName, Context);
517
518 // Finally create the AsmPrinter we'll use to emit the DIEs.
519 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
520 if (!TM)
521 return error("no target machine for target " + TripleName, Context);
522
523 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
524 if (!Asm)
525 return error("no asm printer for target " + TripleName, Context);
526
Frederic Riss25440872015-03-13 23:30:31 +0000527 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000528 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000529 LineSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000530
Frederic Rissc99ea202015-02-28 00:29:11 +0000531 return true;
532}
533
534bool DwarfStreamer::finish() {
535 MS->Finish();
536 return true;
537}
538
Frederic Rissb8b43d52015-03-04 22:07:44 +0000539/// \brief Set the current output section to debug_info and change
540/// the MC Dwarf version to \p DwarfVersion.
541void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
542 MS->SwitchSection(MOFI->getDwarfInfoSection());
543 MC->setDwarfVersion(DwarfVersion);
544}
545
546/// \brief Emit the compilation unit header for \p Unit in the
547/// debug_info section.
548///
549/// A Dwarf scetion header is encoded as:
550/// uint32_t Unit length (omiting this field)
551/// uint16_t Version
552/// uint32_t Abbreviation table offset
553/// uint8_t Address size
554///
555/// Leading to a total of 11 bytes.
556void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
557 unsigned Version = Unit.getOrigUnit().getVersion();
558 switchToDebugInfoSection(Version);
559
560 // Emit size of content not including length itself. The size has
561 // already been computed in CompileUnit::computeOffsets(). Substract
562 // 4 to that size to account for the length field.
563 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
564 Asm->EmitInt16(Version);
565 // We share one abbreviations table across all units so it's always at the
566 // start of the section.
567 Asm->EmitInt32(0);
568 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
569}
570
571/// \brief Emit the \p Abbrevs array as the shared abbreviation table
572/// for the linked Dwarf file.
573void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
574 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
575 Asm->emitDwarfAbbrevs(Abbrevs);
576}
577
578/// \brief Recursively emit the DIE tree rooted at \p Die.
579void DwarfStreamer::emitDIE(DIE &Die) {
580 MS->SwitchSection(MOFI->getDwarfInfoSection());
581 Asm->emitDwarfDIE(Die);
582}
583
Frederic Rissef648462015-03-06 17:56:30 +0000584/// \brief Emit the debug_str section stored in \p Pool.
585void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
586 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
587 for (auto *Entry = Pool.getFirstEntry(); Entry;
588 Entry = Pool.getNextEntry(Entry))
589 Asm->OutStreamer.EmitBytes(
590 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
591}
592
Frederic Riss25440872015-03-13 23:30:31 +0000593/// \brief Emit the debug_range section contents for \p FuncRange by
594/// translating the original \p Entries. The debug_range section
595/// format is totally trivial, consisting just of pairs of address
596/// sized addresses describing the ranges.
597void DwarfStreamer::emitRangesEntries(
598 int64_t UnitPcOffset, uint64_t OrigLowPc,
599 FunctionIntervals::const_iterator FuncRange,
600 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
601 unsigned AddressSize) {
602 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
603
604 // Offset each range by the right amount.
605 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
606 for (const auto &Range : Entries) {
607 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
608 warn("unsupported base address selection operation",
609 "emitting debug_ranges");
610 break;
611 }
612 // Do not emit empty ranges.
613 if (Range.StartAddress == Range.EndAddress)
614 continue;
615
616 // All range entries should lie in the function range.
617 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
618 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
619 warn("inconsistent range data.", "emitting debug_ranges");
620 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
621 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
622 RangesSectionSize += 2 * AddressSize;
623 }
624
625 // Add the terminator entry.
626 MS->EmitIntValue(0, AddressSize);
627 MS->EmitIntValue(0, AddressSize);
628 RangesSectionSize += 2 * AddressSize;
629}
630
Frederic Riss563b1b02015-03-14 03:46:51 +0000631/// \brief Emit the debug_aranges contribution of a unit and
632/// if \p DoDebugRanges is true the debug_range contents for a
633/// compile_unit level DW_AT_ranges attribute (Which are basically the
634/// same thing with a different base address).
635/// Just aggregate all the ranges gathered inside that unit.
636void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
637 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000638 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
639 // Gather the ranges in a vector, so that we can simplify them. The
640 // IntervalMap will have coalesced the non-linked ranges, but here
641 // we want to coalesce the linked addresses.
642 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
643 const auto &FunctionRanges = Unit.getFunctionRanges();
644 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
645 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000646 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
647 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000648
649 // The object addresses where sorted, but again, the linked
650 // addresses might end up in a different order.
651 std::sort(Ranges.begin(), Ranges.end());
652
Frederic Riss563b1b02015-03-14 03:46:51 +0000653 if (!Ranges.empty()) {
654 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
655
656 MCSymbol *BeginLabel = Asm->GetTempSymbol("Barange", Unit.getUniqueID());
657 MCSymbol *EndLabel = Asm->GetTempSymbol("Earange", Unit.getUniqueID());
658
659 unsigned HeaderSize =
660 sizeof(int32_t) + // Size of contents (w/o this field
661 sizeof(int16_t) + // DWARF ARange version number
662 sizeof(int32_t) + // Offset of CU in the .debug_info section
663 sizeof(int8_t) + // Pointer Size (in bytes)
664 sizeof(int8_t); // Segment Size (in bytes)
665
666 unsigned TupleSize = AddressSize * 2;
667 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
668
669 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
670 Asm->OutStreamer.EmitLabel(BeginLabel);
671 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
672 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
673 Asm->EmitInt8(AddressSize); // Address size
674 Asm->EmitInt8(0); // Segment size
675
676 Asm->OutStreamer.EmitFill(Padding, 0x0);
677
678 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
679 ++Range) {
680 uint64_t RangeStart = Range->first;
681 MS->EmitIntValue(RangeStart, AddressSize);
682 while ((Range + 1) != End && Range->second == (Range + 1)->first)
683 ++Range;
684 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
685 }
686
687 // Emit terminator
688 Asm->OutStreamer.EmitIntValue(0, AddressSize);
689 Asm->OutStreamer.EmitIntValue(0, AddressSize);
690 Asm->OutStreamer.EmitLabel(EndLabel);
691 }
692
693 if (!DoDebugRanges)
694 return;
695
696 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
697 // Offset each range by the right amount.
698 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000699 // Emit coalesced ranges.
700 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000701 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000702 while (Range + 1 != End && Range->second == (Range + 1)->first)
703 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000704 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000705 RangesSectionSize += 2 * AddressSize;
706 }
707
708 // Add the terminator entry.
709 MS->EmitIntValue(0, AddressSize);
710 MS->EmitIntValue(0, AddressSize);
711 RangesSectionSize += 2 * AddressSize;
712}
713
Frederic Rissdfb97902015-03-14 15:49:07 +0000714/// \brief Emit location lists for \p Unit and update attribtues to
715/// point to the new entries.
716void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
717 DWARFContext &Dwarf) {
718 const std::vector<std::pair<DIEInteger *, int64_t>> &Attributes =
719 Unit.getLocationAttributes();
720
721 if (Attributes.empty())
722 return;
723
724 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
725
726 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
727 const DWARFSection &InputSec = Dwarf.getLocSection();
728 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
729 DWARFUnit &OrigUnit = Unit.getOrigUnit();
730 const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
731 int64_t UnitPcOffset = 0;
732 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
733 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
734 if (OrigLowPc != -1ULL)
735 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
736
737 for (const auto &Attr : Attributes) {
738 uint32_t Offset = Attr.first->getValue();
739 Attr.first->setValue(LocSectionSize);
740 // This is the quantity to add to the old location address to get
741 // the correct address for the new one.
742 int64_t LocPcOffset = Attr.second + UnitPcOffset;
743 while (Data.isValidOffset(Offset)) {
744 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
745 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
746 LocSectionSize += 2 * AddressSize;
747 if (Low == 0 && High == 0) {
748 Asm->OutStreamer.EmitIntValue(0, AddressSize);
749 Asm->OutStreamer.EmitIntValue(0, AddressSize);
750 break;
751 }
752 Asm->OutStreamer.EmitIntValue(Low + LocPcOffset, AddressSize);
753 Asm->OutStreamer.EmitIntValue(High + LocPcOffset, AddressSize);
754 uint64_t Length = Data.getU16(&Offset);
755 Asm->OutStreamer.EmitIntValue(Length, 2);
756 // Just copy the bytes over.
757 Asm->OutStreamer.EmitBytes(
758 StringRef(InputSec.Data.substr(Offset, Length)));
759 Offset += Length;
760 LocSectionSize += Length + 2;
761 }
762 }
763}
764
Frederic Riss63786b02015-03-15 20:45:43 +0000765void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
766 unsigned MinInstLength,
767 std::vector<DWARFDebugLine::Row> &Rows,
768 unsigned PointerSize) {
769 // Switch to the section where the table will be emitted into.
770 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
771 MCSymbol *LineStartSym = MC->CreateTempSymbol();
772 MCSymbol *LineEndSym = MC->CreateTempSymbol();
773
774 // The first 4 bytes is the total length of the information for this
775 // compilation unit (not including these 4 bytes for the length).
776 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
777 Asm->OutStreamer.EmitLabel(LineStartSym);
778 // Copy Prologue.
779 MS->EmitBytes(PrologueBytes);
780 LineSectionSize += PrologueBytes.size() + 4;
781
Frederic Rissc3820d02015-03-15 22:20:28 +0000782 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000783 raw_svector_ostream EncodingOS(EncodingBuffer);
784
785 if (Rows.empty()) {
786 // We only have the dummy entry, dsymutil emits an entry with a 0
787 // address in that case.
788 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
789 MS->EmitBytes(EncodingOS.str());
790 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000791 MS->EmitLabel(LineEndSym);
792 return;
793 }
794
795 // Line table state machine fields
796 unsigned FileNum = 1;
797 unsigned LastLine = 1;
798 unsigned Column = 0;
799 unsigned IsStatement = 1;
800 unsigned Isa = 0;
801 uint64_t Address = -1ULL;
802
803 unsigned RowsSinceLastSequence = 0;
804
805 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
806 auto &Row = Rows[Idx];
807
808 int64_t AddressDelta;
809 if (Address == -1ULL) {
810 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
811 MS->EmitULEB128IntValue(PointerSize + 1);
812 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
813 MS->EmitIntValue(Row.Address, PointerSize);
814 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
815 AddressDelta = 0;
816 } else {
817 AddressDelta = (Row.Address - Address) / MinInstLength;
818 }
819
820 // FIXME: code copied and transfromed from
821 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
822 // this code, but the current compatibility requirement with
823 // classic dsymutil makes it hard. Revisit that once this
824 // requirement is dropped.
825
826 if (FileNum != Row.File) {
827 FileNum = Row.File;
828 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
829 MS->EmitULEB128IntValue(FileNum);
830 LineSectionSize += 1 + getULEB128Size(FileNum);
831 }
832 if (Column != Row.Column) {
833 Column = Row.Column;
834 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
835 MS->EmitULEB128IntValue(Column);
836 LineSectionSize += 1 + getULEB128Size(Column);
837 }
838
839 // FIXME: We should handle the discriminator here, but dsymutil
840 // doesn' consider it, thus ignore it for now.
841
842 if (Isa != Row.Isa) {
843 Isa = Row.Isa;
844 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
845 MS->EmitULEB128IntValue(Isa);
846 LineSectionSize += 1 + getULEB128Size(Isa);
847 }
848 if (IsStatement != Row.IsStmt) {
849 IsStatement = Row.IsStmt;
850 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
851 LineSectionSize += 1;
852 }
853 if (Row.BasicBlock) {
854 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
855 LineSectionSize += 1;
856 }
857
858 if (Row.PrologueEnd) {
859 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
860 LineSectionSize += 1;
861 }
862
863 if (Row.EpilogueBegin) {
864 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
865 LineSectionSize += 1;
866 }
867
868 int64_t LineDelta = int64_t(Row.Line) - LastLine;
869 if (!Row.EndSequence) {
870 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
871 MS->EmitBytes(EncodingOS.str());
872 LineSectionSize += EncodingBuffer.size();
873 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000874 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000875 Address = Row.Address;
876 LastLine = Row.Line;
877 RowsSinceLastSequence++;
878 } else {
879 if (LineDelta) {
880 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
881 MS->EmitSLEB128IntValue(LineDelta);
882 LineSectionSize += 1 + getSLEB128Size(LineDelta);
883 }
884 if (AddressDelta) {
885 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
886 MS->EmitULEB128IntValue(AddressDelta);
887 LineSectionSize += 1 + getULEB128Size(AddressDelta);
888 }
889 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
890 MS->EmitBytes(EncodingOS.str());
891 LineSectionSize += EncodingBuffer.size();
892 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000893 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000894 Address = -1ULL;
895 LastLine = FileNum = IsStatement = 1;
896 RowsSinceLastSequence = Column = Isa = 0;
897 }
898 }
899
900 if (RowsSinceLastSequence) {
901 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
902 MS->EmitBytes(EncodingOS.str());
903 LineSectionSize += EncodingBuffer.size();
904 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000905 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000906 }
907
908 MS->EmitLabel(LineEndSym);
909}
910
Frederic Rissbce93ff2015-03-16 02:05:10 +0000911/// \brief Emit the pubnames or pubtypes section contribution for \p
912/// Unit into \p Sec. The data is provided in \p Names.
913void DwarfStreamer::emitPubSectionForUnit(
914 const MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
915 const std::vector<CompileUnit::AccelInfo> &Names) {
916 if (Names.empty())
917 return;
918
919 // Start the dwarf pubnames section.
920 Asm->OutStreamer.SwitchSection(Sec);
921 MCSymbol *BeginLabel =
922 Asm->GetTempSymbol("pub" + SecName + "_begin", Unit.getUniqueID());
923 MCSymbol *EndLabel =
924 Asm->GetTempSymbol("pub" + SecName + "_end", Unit.getUniqueID());
925
926 bool HeaderEmitted = false;
927 // Emit the pubnames for this compilation unit.
928 for (const auto &Name : Names) {
929 if (Name.SkipPubSection)
930 continue;
931
932 if (!HeaderEmitted) {
933 // Emit the header.
934 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
935 Asm->OutStreamer.EmitLabel(BeginLabel);
936 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
937 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
938 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
939 HeaderEmitted = true;
940 }
941 Asm->EmitInt32(Name.Die->getOffset());
942 Asm->OutStreamer.EmitBytes(
943 StringRef(Name.Name.data(), Name.Name.size() + 1));
944 }
945
946 if (!HeaderEmitted)
947 return;
948 Asm->EmitInt32(0); // End marker.
949 Asm->OutStreamer.EmitLabel(EndLabel);
950}
951
952/// \brief Emit .debug_pubnames for \p Unit.
953void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
954 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
955 "names", Unit, Unit.getPubnames());
956}
957
958/// \brief Emit .debug_pubtypes for \p Unit.
959void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
960 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
961 "types", Unit, Unit.getPubtypes());
962}
963
Frederic Rissd3455182015-01-28 18:27:01 +0000964/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000965///
966/// The link of the dwarf information from the object files will be
967/// driven by the selection of 'root DIEs', which are DIEs that
968/// describe variables or functions that are present in the linked
969/// binary (and thus have entries in the debug map). All the debug
970/// information that will be linked (the DIEs, but also the line
971/// tables, ranges, ...) is derived from that set of root DIEs.
972///
973/// The root DIEs are identified because they contain relocations that
974/// correspond to a debug map entry at specific places (the low_pc for
975/// a function, the location for a variable). These relocations are
976/// called ValidRelocs in the DwarfLinker and are gathered as a very
977/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +0000978class DwarfLinker {
979public:
Frederic Rissb9818322015-02-28 00:29:07 +0000980 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
981 : OutputFilename(OutputFilename), Options(Options),
982 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +0000983
Frederic Rissb8b43d52015-03-04 22:07:44 +0000984 ~DwarfLinker() {
985 for (auto *Abbrev : Abbreviations)
986 delete Abbrev;
987 }
988
Frederic Rissd3455182015-01-28 18:27:01 +0000989 /// \brief Link the contents of the DebugMap.
990 bool link(const DebugMap &);
991
992private:
Frederic Riss563cba62015-01-28 22:15:14 +0000993 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +0000994 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +0000995
996 /// \brief Called at the end of a debug object link.
997 void endDebugObject();
998
Frederic Riss1036e642015-02-13 23:18:22 +0000999 /// \defgroup FindValidRelocations Translate debug map into a list
1000 /// of relevant relocations
1001 ///
1002 /// @{
1003 struct ValidReloc {
1004 uint32_t Offset;
1005 uint32_t Size;
1006 uint64_t Addend;
1007 const DebugMapObject::DebugMapEntry *Mapping;
1008
1009 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1010 const DebugMapObject::DebugMapEntry *Mapping)
1011 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1012
1013 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1014 };
1015
1016 /// \brief The valid relocations for the current DebugMapObject.
1017 /// This vector is sorted by relocation offset.
1018 std::vector<ValidReloc> ValidRelocs;
1019
1020 /// \brief Index into ValidRelocs of the next relocation to
1021 /// consider. As we walk the DIEs in acsending file offset and as
1022 /// ValidRelocs is sorted by file offset, keeping this index
1023 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001024 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001025 unsigned NextValidReloc;
1026
1027 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1028 const DebugMapObject &DMO);
1029
1030 bool findValidRelocs(const object::SectionRef &Section,
1031 const object::ObjectFile &Obj,
1032 const DebugMapObject &DMO);
1033
1034 void findValidRelocsMachO(const object::SectionRef &Section,
1035 const object::MachOObjectFile &Obj,
1036 const DebugMapObject &DMO);
1037 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001038
Frederic Riss84c09a52015-02-13 23:18:34 +00001039 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1040 ///
1041 /// @{
1042 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1043 /// keep. Store that information in \p CU's DIEInfo.
1044 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1045 const DebugMapObject &DMO, CompileUnit &CU,
1046 unsigned Flags);
1047
1048 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1049 enum TravesalFlags {
1050 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1051 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1052 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1053 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1054 };
1055
1056 /// \brief Mark the passed DIE as well as all the ones it depends on
1057 /// as kept.
1058 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1059 CompileUnit::DIEInfo &MyInfo,
1060 const DebugMapObject &DMO, CompileUnit &CU,
1061 unsigned Flags);
1062
1063 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1064 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1065 unsigned Flags);
1066
1067 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1068 CompileUnit &Unit,
1069 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1070
1071 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1072 CompileUnit &Unit,
1073 CompileUnit::DIEInfo &MyInfo,
1074 unsigned Flags);
1075
1076 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1077 CompileUnit::DIEInfo &Info);
1078 /// @}
1079
Frederic Rissb8b43d52015-03-04 22:07:44 +00001080 /// \defgroup Linking Methods used to link the debug information
1081 ///
1082 /// @{
1083 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1084 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1085 /// stripped out and addresses have been rewritten according to the
1086 /// debug map.
1087 ///
1088 /// \param OutOffset is the offset the cloned DIE in the output
1089 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001090 /// \param PCOffset (while cloning a function scope) is the offset
1091 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001092 ///
1093 /// \returns the root of the cloned tree.
1094 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001095 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001096
1097 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1098
Frederic Riss31da3242015-03-11 18:45:52 +00001099 /// \brief Information gathered and exchanged between the various
1100 /// clone*Attributes helpers about the attributes of a particular DIE.
1101 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001102 const char *Name, *MangledName; ///< Names.
1103 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1104
Frederic Riss31da3242015-03-11 18:45:52 +00001105 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1106 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1107
Frederic Rissbce93ff2015-03-16 02:05:10 +00001108 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1109 bool IsDeclaration; ///< Is this DIE only a declaration?
1110
1111 AttributesInfo()
1112 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1113 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1114 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001115 };
1116
Frederic Rissb8b43d52015-03-04 22:07:44 +00001117 /// \brief Helper for cloneDIE.
1118 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1119 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001120 const AttributeSpec AttrSpec, unsigned AttrSize,
1121 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001122
1123 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001124 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1125 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001126
1127 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001128 unsigned
1129 cloneDieReferenceAttribute(DIE &Die,
1130 const DWARFDebugInfoEntryMinimal &InputDIE,
1131 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001132 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001133
1134 /// \brief Helper for cloneDIE.
1135 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1136 const DWARFFormValue &Val, unsigned AttrSize);
1137
1138 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001139 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1140 const DWARFFormValue &Val,
1141 const CompileUnit &Unit, AttributesInfo &Info);
1142
1143 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001144 unsigned cloneScalarAttribute(DIE &Die,
1145 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001146 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001147 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001148 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001149
Frederic Riss23e20e92015-03-07 01:25:09 +00001150 /// \brief Helper for cloneDIE.
1151 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1152 bool isLittleEndian);
1153
Frederic Rissb8b43d52015-03-04 22:07:44 +00001154 /// \brief Assign an abbreviation number to \p Abbrev
1155 void AssignAbbrev(DIEAbbrev &Abbrev);
1156
1157 /// \brief FoldingSet that uniques the abbreviations.
1158 FoldingSet<DIEAbbrev> AbbreviationsSet;
1159 /// \brief Storage for the unique Abbreviations.
1160 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1161 /// be changed to a vecot of unique_ptrs.
1162 std::vector<DIEAbbrev *> Abbreviations;
1163
Frederic Riss25440872015-03-13 23:30:31 +00001164 /// \brief Compute and emit debug_ranges section for \p Unit, and
1165 /// patch the attributes referencing it.
1166 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1167
1168 /// \brief Generate and emit the DW_AT_ranges attribute for a
1169 /// compile_unit if it had one.
1170 void generateUnitRanges(CompileUnit &Unit) const;
1171
Frederic Riss63786b02015-03-15 20:45:43 +00001172 /// \brief Extract the line tables fromt he original dwarf, extract
1173 /// the relevant parts according to the linked function ranges and
1174 /// emit the result in the debug_line section.
1175 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1176
Frederic Rissbce93ff2015-03-16 02:05:10 +00001177 /// \brief Emit the accelerator entries for \p Unit.
1178 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1179
Frederic Rissb8b43d52015-03-04 22:07:44 +00001180 /// \brief DIELoc objects that need to be destructed (but not freed!).
1181 std::vector<DIELoc *> DIELocs;
1182 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1183 std::vector<DIEBlock *> DIEBlocks;
1184 /// \brief Allocator used for all the DIEValue objects.
1185 BumpPtrAllocator DIEAlloc;
1186 /// @}
1187
Frederic Riss1b9da422015-02-13 23:18:29 +00001188 /// \defgroup Helpers Various helper methods.
1189 ///
1190 /// @{
1191 const DWARFDebugInfoEntryMinimal *
1192 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1193 const DWARFDebugInfoEntryMinimal &DIE,
1194 CompileUnit *&ReferencedCU);
1195
1196 CompileUnit *getUnitForOffset(unsigned Offset);
1197
Frederic Rissbce93ff2015-03-16 02:05:10 +00001198 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1199 AttributesInfo &Info);
1200
Frederic Riss1b9da422015-02-13 23:18:29 +00001201 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001202 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001203
1204 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +00001205 /// @}
1206
Frederic Riss563cba62015-01-28 22:15:14 +00001207private:
Frederic Rissd3455182015-01-28 18:27:01 +00001208 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001209 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001210 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001211 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001212
1213 /// The units of the current debug map object.
1214 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001215
1216 /// The debug map object curently under consideration.
1217 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001218
1219 /// \brief The Dwarf string pool
1220 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001221
1222 /// \brief This map is keyed by the entry PC of functions in that
1223 /// debug object and the associated value is a pair storing the
1224 /// corresponding end PC and the offset to apply to get the linked
1225 /// address.
1226 ///
1227 /// See startDebugObject() for a more complete description of its use.
1228 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Rissd3455182015-01-28 18:27:01 +00001229};
1230
Frederic Riss1b9da422015-02-13 23:18:29 +00001231/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1232/// returning our CompileUnit object instead.
1233CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1234 auto CU =
1235 std::upper_bound(Units.begin(), Units.end(), Offset,
1236 [](uint32_t LHS, const CompileUnit &RHS) {
1237 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1238 });
1239 return CU != Units.end() ? &*CU : nullptr;
1240}
1241
1242/// \brief Resolve the DIE attribute reference that has been
1243/// extracted in \p RefValue. The resulting DIE migh be in another
1244/// CompileUnit which is stored into \p ReferencedCU.
1245/// \returns null if resolving fails for any reason.
1246const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1247 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1248 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1249 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1250 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1251
1252 if ((RefCU = getUnitForOffset(RefOffset)))
1253 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1254 return RefDie;
1255
1256 reportWarning("could not find referenced DIE", &Unit, &DIE);
1257 return nullptr;
1258}
1259
Frederic Rissbce93ff2015-03-16 02:05:10 +00001260/// \brief Get the potential name and mangled name for the entity
1261/// described by \p Die and store them in \Info if they are not
1262/// already there.
1263/// \returns is a name was found.
1264bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1265 DWARFUnit &U, AttributesInfo &Info) {
1266 // FIXME: a bit wastefull as the first getName might return the
1267 // short name.
1268 if (!Info.MangledName &&
1269 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1270 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1271
1272 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1273 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1274
1275 return Info.Name || Info.MangledName;
1276}
1277
Frederic Riss1b9da422015-02-13 23:18:29 +00001278/// \brief Report a warning to the user, optionaly including
1279/// information about a specific \p DIE related to the warning.
1280void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001281 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001282 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001283 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001284 Context = CurrentDebugObject->getObjectFilename();
1285 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001286
Frederic Rissb9818322015-02-28 00:29:07 +00001287 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001288 return;
1289
1290 errs() << " in DIE:\n";
1291 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1292 6 /* Indent */);
1293}
1294
Frederic Rissc99ea202015-02-28 00:29:11 +00001295bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1296 if (Options.NoOutput)
1297 return true;
1298
Frederic Rissb52cf522015-02-28 00:42:37 +00001299 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001300 return Streamer->init(TheTriple, OutputFilename);
1301}
1302
Frederic Riss563cba62015-01-28 22:15:14 +00001303/// \brief Recursive helper to gather the child->parent relationships in the
1304/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001305static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1306 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +00001307 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1308 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1309
1310 if (DIE->hasChildren())
1311 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1312 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +00001313 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +00001314}
1315
Frederic Riss84c09a52015-02-13 23:18:34 +00001316static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1317 switch (Tag) {
1318 default:
1319 return false;
1320 case dwarf::DW_TAG_subprogram:
1321 case dwarf::DW_TAG_lexical_block:
1322 case dwarf::DW_TAG_subroutine_type:
1323 case dwarf::DW_TAG_structure_type:
1324 case dwarf::DW_TAG_class_type:
1325 case dwarf::DW_TAG_union_type:
1326 return true;
1327 }
1328 llvm_unreachable("Invalid Tag");
1329}
1330
Frederic Riss63786b02015-03-15 20:45:43 +00001331void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001332 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001333 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001334 // Iterate over the debug map entries and put all the ones that are
1335 // functions (because they have a size) into the Ranges map. This
1336 // map is very similar to the FunctionRanges that are stored in each
1337 // unit, with 2 notable differences:
1338 // - obviously this one is global, while the other ones are per-unit.
1339 // - this one contains not only the functions described in the DIE
1340 // tree, but also the ones that are only in the debug map.
1341 // The latter information is required to reproduce dsymutil's logic
1342 // while linking line tables. The cases where this information
1343 // matters look like bugs that need to be investigated, but for now
1344 // we need to reproduce dsymutil's behavior.
1345 // FIXME: Once we understood exactly if that information is needed,
1346 // maybe totally remove this (or try to use it to do a real
1347 // -gline-tables-only on Darwin.
1348 for (const auto &Entry : Obj.symbols()) {
1349 const auto &Mapping = Entry.getValue();
1350 if (Mapping.Size)
1351 Ranges[Mapping.ObjectAddress] = std::make_pair(
1352 Mapping.ObjectAddress + Mapping.Size,
1353 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1354 }
Frederic Riss563cba62015-01-28 22:15:14 +00001355}
1356
Frederic Riss1036e642015-02-13 23:18:22 +00001357void DwarfLinker::endDebugObject() {
1358 Units.clear();
1359 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001360 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001361
1362 for (auto *Block : DIEBlocks)
1363 Block->~DIEBlock();
1364 for (auto *Loc : DIELocs)
1365 Loc->~DIELoc();
1366
1367 DIEBlocks.clear();
1368 DIELocs.clear();
1369 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001370}
1371
1372/// \brief Iterate over the relocations of the given \p Section and
1373/// store the ones that correspond to debug map entries into the
1374/// ValidRelocs array.
1375void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1376 const object::MachOObjectFile &Obj,
1377 const DebugMapObject &DMO) {
1378 StringRef Contents;
1379 Section.getContents(Contents);
1380 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1381
1382 for (const object::RelocationRef &Reloc : Section.relocations()) {
1383 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1384 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1385 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1386 uint64_t Offset64;
1387 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001388 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001389 continue;
1390 }
1391 uint32_t Offset = Offset64;
1392 // Mach-o uses REL relocations, the addend is at the relocation offset.
1393 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1394
1395 auto Sym = Reloc.getSymbol();
1396 if (Sym != Obj.symbol_end()) {
1397 StringRef SymbolName;
1398 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001399 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001400 continue;
1401 }
1402 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1403 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1404 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1405 // Do not store the addend. The addend was the address of the
1406 // symbol in the object file, the address in the binary that is
1407 // stored in the debug map doesn't need to be offseted.
1408 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1409 }
1410 }
1411}
1412
1413/// \brief Dispatch the valid relocation finding logic to the
1414/// appropriate handler depending on the object file format.
1415bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1416 const object::ObjectFile &Obj,
1417 const DebugMapObject &DMO) {
1418 // Dispatch to the right handler depending on the file type.
1419 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1420 findValidRelocsMachO(Section, *MachOObj, DMO);
1421 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001422 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001423
1424 if (ValidRelocs.empty())
1425 return false;
1426
1427 // Sort the relocations by offset. We will walk the DIEs linearly in
1428 // the file, this allows us to just keep an index in the relocation
1429 // array that we advance during our walk, rather than resorting to
1430 // some associative container. See DwarfLinker::NextValidReloc.
1431 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1432 return true;
1433}
1434
1435/// \brief Look for relocations in the debug_info section that match
1436/// entries in the debug map. These relocations will drive the Dwarf
1437/// link by indicating which DIEs refer to symbols present in the
1438/// linked binary.
1439/// \returns wether there are any valid relocations in the debug info.
1440bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1441 const DebugMapObject &DMO) {
1442 // Find the debug_info section.
1443 for (const object::SectionRef &Section : Obj.sections()) {
1444 StringRef SectionName;
1445 Section.getName(SectionName);
1446 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1447 if (SectionName != "debug_info")
1448 continue;
1449 return findValidRelocs(Section, Obj, DMO);
1450 }
1451 return false;
1452}
Frederic Riss563cba62015-01-28 22:15:14 +00001453
Frederic Riss84c09a52015-02-13 23:18:34 +00001454/// \brief Checks that there is a relocation against an actual debug
1455/// map entry between \p StartOffset and \p NextOffset.
1456///
1457/// This function must be called with offsets in strictly ascending
1458/// order because it never looks back at relocations it already 'went past'.
1459/// \returns true and sets Info.InDebugMap if it is the case.
1460bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1461 CompileUnit::DIEInfo &Info) {
1462 assert(NextValidReloc == 0 ||
1463 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1464 if (NextValidReloc >= ValidRelocs.size())
1465 return false;
1466
1467 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1468
1469 // We might need to skip some relocs that we didn't consider. For
1470 // example the high_pc of a discarded DIE might contain a reloc that
1471 // is in the list because it actually corresponds to the start of a
1472 // function that is in the debug map.
1473 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1474 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1475
1476 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1477 return false;
1478
1479 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +00001480 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001481 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1482 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1483 ValidReloc.Mapping->getValue().ObjectAddress,
1484 ValidReloc.Mapping->getValue().BinaryAddress);
1485
Frederic Riss31da3242015-03-11 18:45:52 +00001486 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1487 ValidReloc.Addend -
1488 ValidReloc.Mapping->getValue().ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001489 Info.InDebugMap = true;
1490 return true;
1491}
1492
1493/// \brief Get the starting and ending (exclusive) offset for the
1494/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1495/// supposed to point to the position of the first attribute described
1496/// by \p Abbrev.
1497/// \return [StartOffset, EndOffset) as a pair.
1498static std::pair<uint32_t, uint32_t>
1499getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1500 unsigned Offset, const DWARFUnit &Unit) {
1501 DataExtractor Data = Unit.getDebugInfoExtractor();
1502
1503 for (unsigned i = 0; i < Idx; ++i)
1504 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1505
1506 uint32_t End = Offset;
1507 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1508
1509 return std::make_pair(Offset, End);
1510}
1511
1512/// \brief Check if a variable describing DIE should be kept.
1513/// \returns updated TraversalFlags.
1514unsigned DwarfLinker::shouldKeepVariableDIE(
1515 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1516 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1517 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1518
1519 // Global variables with constant value can always be kept.
1520 if (!(Flags & TF_InFunctionScope) &&
1521 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1522 MyInfo.InDebugMap = true;
1523 return Flags | TF_Keep;
1524 }
1525
1526 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1527 if (LocationIdx == -1U)
1528 return Flags;
1529
1530 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1531 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1532 uint32_t LocationOffset, LocationEndOffset;
1533 std::tie(LocationOffset, LocationEndOffset) =
1534 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1535
1536 // See if there is a relocation to a valid debug map entry inside
1537 // this variable's location. The order is important here. We want to
1538 // always check in the variable has a valid relocation, so that the
1539 // DIEInfo is filled. However, we don't want a static variable in a
1540 // function to force us to keep the enclosing function.
1541 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1542 (Flags & TF_InFunctionScope))
1543 return Flags;
1544
Frederic Rissb9818322015-02-28 00:29:07 +00001545 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001546 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1547
1548 return Flags | TF_Keep;
1549}
1550
1551/// \brief Check if a function describing DIE should be kept.
1552/// \returns updated TraversalFlags.
1553unsigned DwarfLinker::shouldKeepSubprogramDIE(
1554 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1555 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1556 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1557
1558 Flags |= TF_InFunctionScope;
1559
1560 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1561 if (LowPcIdx == -1U)
1562 return Flags;
1563
1564 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1565 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1566 uint32_t LowPcOffset, LowPcEndOffset;
1567 std::tie(LowPcOffset, LowPcEndOffset) =
1568 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1569
1570 uint64_t LowPc =
1571 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1572 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1573 if (LowPc == -1ULL ||
1574 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1575 return Flags;
1576
Frederic Rissb9818322015-02-28 00:29:07 +00001577 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001578 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1579
Frederic Riss1af75f72015-03-12 18:45:10 +00001580 Flags |= TF_Keep;
1581
1582 DWARFFormValue HighPcValue;
1583 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1584 reportWarning("Function without high_pc. Range will be discarded.\n",
1585 &OrigUnit, &DIE);
1586 return Flags;
1587 }
1588
1589 uint64_t HighPc;
1590 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1591 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1592 } else {
1593 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1594 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1595 }
1596
Frederic Riss63786b02015-03-15 20:45:43 +00001597 // Replace the debug map range with a more accurate one.
1598 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001599 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1600 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001601}
1602
1603/// \brief Check if a DIE should be kept.
1604/// \returns updated TraversalFlags.
1605unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1606 CompileUnit &Unit,
1607 CompileUnit::DIEInfo &MyInfo,
1608 unsigned Flags) {
1609 switch (DIE.getTag()) {
1610 case dwarf::DW_TAG_constant:
1611 case dwarf::DW_TAG_variable:
1612 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1613 case dwarf::DW_TAG_subprogram:
1614 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1615 case dwarf::DW_TAG_module:
1616 case dwarf::DW_TAG_imported_module:
1617 case dwarf::DW_TAG_imported_declaration:
1618 case dwarf::DW_TAG_imported_unit:
1619 // We always want to keep these.
1620 return Flags | TF_Keep;
1621 }
1622
1623 return Flags;
1624}
1625
Frederic Riss84c09a52015-02-13 23:18:34 +00001626/// \brief Mark the passed DIE as well as all the ones it depends on
1627/// as kept.
1628///
1629/// This function is called by lookForDIEsToKeep on DIEs that are
1630/// newly discovered to be needed in the link. It recursively calls
1631/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1632/// TraversalFlags to inform it that it's not doing the primary DIE
1633/// tree walk.
1634void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1635 CompileUnit::DIEInfo &MyInfo,
1636 const DebugMapObject &DMO,
1637 CompileUnit &CU, unsigned Flags) {
1638 const DWARFUnit &Unit = CU.getOrigUnit();
1639 MyInfo.Keep = true;
1640
1641 // First mark all the parent chain as kept.
1642 unsigned AncestorIdx = MyInfo.ParentIdx;
1643 while (!CU.getInfo(AncestorIdx).Keep) {
1644 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1645 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1646 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1647 }
1648
1649 // Then we need to mark all the DIEs referenced by this DIE's
1650 // attributes as kept.
1651 DataExtractor Data = Unit.getDebugInfoExtractor();
1652 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1653 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1654
1655 // Mark all DIEs referenced through atttributes as kept.
1656 for (const auto &AttrSpec : Abbrev->attributes()) {
1657 DWARFFormValue Val(AttrSpec.Form);
1658
1659 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1660 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1661 continue;
1662 }
1663
1664 Val.extractValue(Data, &Offset, &Unit);
1665 CompileUnit *ReferencedCU;
1666 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1667 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1668 TF_Keep | TF_DependencyWalk);
1669 }
1670}
1671
1672/// \brief Recursively walk the \p DIE tree and look for DIEs to
1673/// keep. Store that information in \p CU's DIEInfo.
1674///
1675/// This function is the entry point of the DIE selection
1676/// algorithm. It is expected to walk the DIE tree in file order and
1677/// (though the mediation of its helper) call hasValidRelocation() on
1678/// each DIE that might be a 'root DIE' (See DwarfLinker class
1679/// comment).
1680/// While walking the dependencies of root DIEs, this function is
1681/// also called, but during these dependency walks the file order is
1682/// not respected. The TF_DependencyWalk flag tells us which kind of
1683/// traversal we are currently doing.
1684void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1685 const DebugMapObject &DMO, CompileUnit &CU,
1686 unsigned Flags) {
1687 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1688 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1689 bool AlreadyKept = MyInfo.Keep;
1690
1691 // If the Keep flag is set, we are marking a required DIE's
1692 // dependencies. If our target is already marked as kept, we're all
1693 // set.
1694 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1695 return;
1696
1697 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1698 // because it would screw up the relocation finding logic.
1699 if (!(Flags & TF_DependencyWalk))
1700 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1701
1702 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1703 if (!AlreadyKept && (Flags & TF_Keep))
1704 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1705
1706 // The TF_ParentWalk flag tells us that we are currently walking up
1707 // the parent chain of a required DIE, and we don't want to mark all
1708 // the children of the parents as kept (consider for example a
1709 // DW_TAG_namespace node in the parent chain). There are however a
1710 // set of DIE types for which we want to ignore that directive and still
1711 // walk their children.
1712 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1713 Flags &= ~TF_ParentWalk;
1714
1715 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1716 return;
1717
1718 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1719 Child = Child->getSibling())
1720 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1721}
1722
Frederic Rissb8b43d52015-03-04 22:07:44 +00001723/// \brief Assign an abbreviation numer to \p Abbrev.
1724///
1725/// Our DIEs get freed after every DebugMapObject has been processed,
1726/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1727/// the instances hold by the DIEs. When we encounter an abbreviation
1728/// that we don't know, we create a permanent copy of it.
1729void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1730 // Check the set for priors.
1731 FoldingSetNodeID ID;
1732 Abbrev.Profile(ID);
1733 void *InsertToken;
1734 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1735
1736 // If it's newly added.
1737 if (InSet) {
1738 // Assign existing abbreviation number.
1739 Abbrev.setNumber(InSet->getNumber());
1740 } else {
1741 // Add to abbreviation list.
1742 Abbreviations.push_back(
1743 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1744 for (const auto &Attr : Abbrev.getData())
1745 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1746 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1747 // Assign the unique abbreviation number.
1748 Abbrev.setNumber(Abbreviations.size());
1749 Abbreviations.back()->setNumber(Abbreviations.size());
1750 }
1751}
1752
1753/// \brief Clone a string attribute described by \p AttrSpec and add
1754/// it to \p Die.
1755/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001756unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1757 const DWARFFormValue &Val,
1758 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001759 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001760 const char *String = *Val.getAsCString(&U);
1761 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001762 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Frederic Rissef648462015-03-06 17:56:30 +00001763 new (DIEAlloc) DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001764 return 4;
1765}
1766
1767/// \brief Clone an attribute referencing another DIE and add
1768/// it to \p Die.
1769/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001770unsigned DwarfLinker::cloneDieReferenceAttribute(
1771 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1772 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001773 CompileUnit &Unit) {
1774 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
Frederic Riss9833de62015-03-06 23:22:53 +00001775 DIE *NewRefDie = nullptr;
1776 CompileUnit *RefUnit = nullptr;
1777 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1778
1779 if (!(RefUnit = getUnitForOffset(Ref)) ||
1780 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1781 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1782 if (!AttributeString)
1783 AttributeString = "DW_AT_???";
1784 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1785 ". Dropping.",
Frederic Riss6afcfce2015-03-13 18:35:57 +00001786 &Unit.getOrigUnit(), &InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001787 return 0;
1788 }
1789
1790 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1791 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1792 if (!RefInfo.Clone) {
1793 assert(Ref > InputDIE.getOffset());
1794 // We haven't cloned this DIE yet. Just create an empty one and
1795 // store it. It'll get really cloned when we process it.
1796 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1797 }
1798 NewRefDie = RefInfo.Clone;
1799
1800 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1801 // We cannot currently rely on a DIEEntry to emit ref_addr
1802 // references, because the implementation calls back to DwarfDebug
1803 // to find the unit offset. (We don't have a DwarfDebug)
1804 // FIXME: we should be able to design DIEEntry reliance on
1805 // DwarfDebug away.
1806 DIEInteger *Attr;
1807 if (Ref < InputDIE.getOffset()) {
1808 // We must have already cloned that DIE.
1809 uint32_t NewRefOffset =
1810 RefUnit->getStartOffset() + NewRefDie->getOffset();
1811 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1812 } else {
1813 // A forward reference. Note and fixup later.
1814 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
Frederic Riss6afcfce2015-03-13 18:35:57 +00001815 Unit.noteForwardReference(NewRefDie, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +00001816 }
1817 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1818 Attr);
1819 return AttrSize;
1820 }
1821
Frederic Rissb8b43d52015-03-04 22:07:44 +00001822 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss9833de62015-03-06 23:22:53 +00001823 new (DIEAlloc) DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001824 return AttrSize;
1825}
1826
1827/// \brief Clone an attribute of block form (locations, constants) and add
1828/// it to \p Die.
1829/// \returns the size of the new attribute.
1830unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1831 const DWARFFormValue &Val,
1832 unsigned AttrSize) {
1833 DIE *Attr;
1834 DIEValue *Value;
1835 DIELoc *Loc = nullptr;
1836 DIEBlock *Block = nullptr;
1837 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001838 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001839 Loc = new (DIEAlloc) DIELoc();
1840 DIELocs.push_back(Loc);
1841 } else {
1842 Block = new (DIEAlloc) DIEBlock();
1843 DIEBlocks.push_back(Block);
1844 }
1845 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1846 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1847 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1848 for (auto Byte : Bytes)
1849 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1850 new (DIEAlloc) DIEInteger(Byte));
1851 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1852 // the DIE class, this if could be replaced by
1853 // Attr->setSize(Bytes.size()).
1854 if (Streamer) {
1855 if (Loc)
1856 Loc->ComputeSize(&Streamer->getAsmPrinter());
1857 else
1858 Block->ComputeSize(&Streamer->getAsmPrinter());
1859 }
1860 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1861 Value);
1862 return AttrSize;
1863}
1864
Frederic Riss31da3242015-03-11 18:45:52 +00001865/// \brief Clone an address attribute and add it to \p Die.
1866/// \returns the size of the new attribute.
1867unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1868 const DWARFFormValue &Val,
1869 const CompileUnit &Unit,
1870 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001871 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00001872 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1873 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1874 Die.getTag() == dwarf::DW_TAG_lexical_block)
1875 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001876 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1877 Addr = Unit.getLowPc();
1878 if (Addr == UINT64_MAX)
1879 return 0;
1880 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00001881 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00001882 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001883 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1884 if (uint64_t HighPc = Unit.getHighPc())
1885 Addr = HighPc;
1886 else
1887 return 0;
1888 } else
1889 // If we have a high_pc recorded for the input DIE, use
1890 // it. Otherwise (when no relocations where applied) just use the
1891 // one we just decoded.
1892 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00001893 }
1894
1895 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1896 static_cast<dwarf::Form>(AttrSpec.Form),
1897 new (DIEAlloc) DIEInteger(Addr));
1898 return Unit.getOrigUnit().getAddressByteSize();
1899}
1900
Frederic Rissb8b43d52015-03-04 22:07:44 +00001901/// \brief Clone a scalar attribute and add it to \p Die.
1902/// \returns the size of the new attribute.
1903unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00001904 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00001905 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001906 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001907 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001908 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1909 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1910 if (Unit.getLowPc() == -1ULL)
1911 return 0;
1912 // Dwarf >= 4 high_pc is an size, not an address.
1913 Value = Unit.getHighPc() - Unit.getLowPc();
1914 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00001915 Value = *Val.getAsSectionOffset();
1916 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1917 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001918 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1919 Value = *OptionalValue;
1920 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001921 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1922 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001923 return 0;
1924 }
Frederic Riss25440872015-03-13 23:30:31 +00001925 DIEInteger *Attr = new (DIEAlloc) DIEInteger(Value);
1926 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
1927 Unit.noteRangeAttribute(Die, Attr);
Frederic Rissdfb97902015-03-14 15:49:07 +00001928 // A more generic way to check for location attributes would be
1929 // nice, but it's very unlikely that any other attribute needs a
1930 // location list.
1931 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1932 AttrSpec.Attr == dwarf::DW_AT_frame_base)
1933 Unit.noteLocationAttribute(Attr, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001934 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1935 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00001936
Frederic Rissb8b43d52015-03-04 22:07:44 +00001937 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss25440872015-03-13 23:30:31 +00001938 Attr);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001939 return AttrSize;
1940}
1941
1942/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1943/// value \p Val, and add it to \p Die.
1944/// \returns the size of the cloned attribute.
1945unsigned DwarfLinker::cloneAttribute(DIE &Die,
1946 const DWARFDebugInfoEntryMinimal &InputDIE,
1947 CompileUnit &Unit,
1948 const DWARFFormValue &Val,
1949 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00001950 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001951 const DWARFUnit &U = Unit.getOrigUnit();
1952
1953 switch (AttrSpec.Form) {
1954 case dwarf::DW_FORM_strp:
1955 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00001956 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001957 case dwarf::DW_FORM_ref_addr:
1958 case dwarf::DW_FORM_ref1:
1959 case dwarf::DW_FORM_ref2:
1960 case dwarf::DW_FORM_ref4:
1961 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00001962 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001963 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001964 case dwarf::DW_FORM_block:
1965 case dwarf::DW_FORM_block1:
1966 case dwarf::DW_FORM_block2:
1967 case dwarf::DW_FORM_block4:
1968 case dwarf::DW_FORM_exprloc:
1969 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1970 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00001971 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001972 case dwarf::DW_FORM_data1:
1973 case dwarf::DW_FORM_data2:
1974 case dwarf::DW_FORM_data4:
1975 case dwarf::DW_FORM_data8:
1976 case dwarf::DW_FORM_udata:
1977 case dwarf::DW_FORM_sdata:
1978 case dwarf::DW_FORM_sec_offset:
1979 case dwarf::DW_FORM_flag:
1980 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00001981 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
1982 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001983 default:
1984 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1985 &InputDIE);
1986 }
1987
1988 return 0;
1989}
1990
Frederic Riss23e20e92015-03-07 01:25:09 +00001991/// \brief Apply the valid relocations found by findValidRelocs() to
1992/// the buffer \p Data, taking into account that Data is at \p BaseOffset
1993/// in the debug_info section.
1994///
1995/// Like for findValidRelocs(), this function must be called with
1996/// monotonic \p BaseOffset values.
1997///
1998/// \returns wether any reloc has been applied.
1999bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2000 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002001 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002002 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2003 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002004 if (NextValidReloc >= ValidRelocs.size())
2005 return false;
2006
2007 // Skip relocs that haven't been applied.
2008 while (NextValidReloc < ValidRelocs.size() &&
2009 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2010 ++NextValidReloc;
2011
2012 bool Applied = false;
2013 uint64_t EndOffset = BaseOffset + Data.size();
2014 while (NextValidReloc < ValidRelocs.size() &&
2015 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2016 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2017 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2018 assert(ValidReloc.Offset - BaseOffset < Data.size());
2019 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2020 char Buf[8];
2021 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2022 Value += ValidReloc.Addend;
2023 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2024 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2025 Buf[i] = uint8_t(Value >> (Index * 8));
2026 }
2027 assert(ValidReloc.Size <= sizeof(Buf));
2028 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2029 Applied = true;
2030 }
2031
2032 return Applied;
2033}
2034
Frederic Rissbce93ff2015-03-16 02:05:10 +00002035static bool isTypeTag(uint16_t Tag) {
2036 switch (Tag) {
2037 case dwarf::DW_TAG_array_type:
2038 case dwarf::DW_TAG_class_type:
2039 case dwarf::DW_TAG_enumeration_type:
2040 case dwarf::DW_TAG_pointer_type:
2041 case dwarf::DW_TAG_reference_type:
2042 case dwarf::DW_TAG_string_type:
2043 case dwarf::DW_TAG_structure_type:
2044 case dwarf::DW_TAG_subroutine_type:
2045 case dwarf::DW_TAG_typedef:
2046 case dwarf::DW_TAG_union_type:
2047 case dwarf::DW_TAG_ptr_to_member_type:
2048 case dwarf::DW_TAG_set_type:
2049 case dwarf::DW_TAG_subrange_type:
2050 case dwarf::DW_TAG_base_type:
2051 case dwarf::DW_TAG_const_type:
2052 case dwarf::DW_TAG_constant:
2053 case dwarf::DW_TAG_file_type:
2054 case dwarf::DW_TAG_namelist:
2055 case dwarf::DW_TAG_packed_type:
2056 case dwarf::DW_TAG_volatile_type:
2057 case dwarf::DW_TAG_restrict_type:
2058 case dwarf::DW_TAG_interface_type:
2059 case dwarf::DW_TAG_unspecified_type:
2060 case dwarf::DW_TAG_shared_type:
2061 return true;
2062 default:
2063 break;
2064 }
2065 return false;
2066}
2067
Frederic Rissb8b43d52015-03-04 22:07:44 +00002068/// \brief Recursively clone \p InputDIE's subtrees that have been
2069/// selected to appear in the linked output.
2070///
2071/// \param OutOffset is the Offset where the newly created DIE will
2072/// lie in the linked compile unit.
2073///
2074/// \returns the cloned DIE object or null if nothing was selected.
2075DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002076 CompileUnit &Unit, int64_t PCOffset,
2077 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002078 DWARFUnit &U = Unit.getOrigUnit();
2079 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002080 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002081
2082 // Should the DIE appear in the output?
2083 if (!Unit.getInfo(Idx).Keep)
2084 return nullptr;
2085
2086 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002087 // The DIE might have been already created by a forward reference
2088 // (see cloneDieReferenceAttribute()).
2089 DIE *Die = Info.Clone;
2090 if (!Die)
2091 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
2092 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002093 Die->setOffset(OutOffset);
2094
2095 // Extract and clone every attribute.
2096 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002097 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002098 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002099
2100 // We could copy the data only if we need to aply a relocation to
2101 // it. After testing, it seems there is no performance downside to
2102 // doing the copy unconditionally, and it makes the code simpler.
2103 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2104 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2105 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002106 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2107 // If we applied relocations, we store the value of high_pc that was
2108 // potentially stored in the input DIE. If high_pc is an address
2109 // (Dwarf version == 2), then it might have been relocated to a
2110 // totally unrelated value (because the end address in the object
2111 // file might be start address of another function which got moved
2112 // independantly by the linker). The computation of the actual
2113 // high_pc value is done in cloneAddressAttribute().
2114 AttrInfo.OrigHighPc =
2115 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2116 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002117
2118 // Reset the Offset to 0 as we will be working on the local copy of
2119 // the data.
2120 Offset = 0;
2121
Frederic Rissb8b43d52015-03-04 22:07:44 +00002122 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2123 Offset += getULEB128Size(Abbrev->getCode());
2124
Frederic Riss31da3242015-03-11 18:45:52 +00002125 // We are entering a subprogram. Get and propagate the PCOffset.
2126 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2127 PCOffset = Info.AddrAdjust;
2128 AttrInfo.PCOffset = PCOffset;
2129
Frederic Rissb8b43d52015-03-04 22:07:44 +00002130 for (const auto &AttrSpec : Abbrev->attributes()) {
2131 DWARFFormValue Val(AttrSpec.Form);
2132 uint32_t AttrSize = Offset;
2133 Val.extractValue(Data, &Offset, &U);
2134 AttrSize = Offset - AttrSize;
2135
Frederic Riss31da3242015-03-11 18:45:52 +00002136 OutOffset +=
2137 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002138 }
2139
Frederic Rissbce93ff2015-03-16 02:05:10 +00002140 // Look for accelerator entries.
2141 uint16_t Tag = InputDIE.getTag();
2142 // FIXME: This is slightly wrong. An inline_subroutine without a
2143 // low_pc, but with AT_ranges might be interesting to get into the
2144 // accelerator tables too. For now stick with dsymutil's behavior.
2145 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2146 Tag != dwarf::DW_TAG_compile_unit &&
2147 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2148 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2149 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2150 AttrInfo.MangledNameOffset,
2151 Tag == dwarf::DW_TAG_inlined_subroutine);
2152 if (AttrInfo.Name)
2153 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2154 Tag == dwarf::DW_TAG_inlined_subroutine);
2155 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2156 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2157 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2158 }
2159
Frederic Rissb8b43d52015-03-04 22:07:44 +00002160 DIEAbbrev &NewAbbrev = Die->getAbbrev();
2161 // If a scope DIE is kept, we must have kept at least one child. If
2162 // it's not the case, we'll just be emitting one wasteful end of
2163 // children marker, but things won't break.
2164 if (InputDIE.hasChildren())
2165 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2166 // Assign a permanent abbrev number
2167 AssignAbbrev(Die->getAbbrev());
2168
2169 // Add the size of the abbreviation number to the output offset.
2170 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2171
2172 if (!Abbrev->hasChildren()) {
2173 // Update our size.
2174 Die->setSize(OutOffset - Die->getOffset());
2175 return Die;
2176 }
2177
2178 // Recursively clone children.
2179 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2180 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002181 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002182 Die->addChild(std::unique_ptr<DIE>(Clone));
2183 OutOffset = Clone->getOffset() + Clone->getSize();
2184 }
2185 }
2186
2187 // Account for the end of children marker.
2188 OutOffset += sizeof(int8_t);
2189 // Update our size.
2190 Die->setSize(OutOffset - Die->getOffset());
2191 return Die;
2192}
2193
Frederic Riss25440872015-03-13 23:30:31 +00002194/// \brief Patch the input object file relevant debug_ranges entries
2195/// and emit them in the output file. Update the relevant attributes
2196/// to point at the new entries.
2197void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2198 DWARFContext &OrigDwarf) const {
2199 DWARFDebugRangeList RangeList;
2200 const auto &FunctionRanges = Unit.getFunctionRanges();
2201 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2202 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2203 OrigDwarf.isLittleEndian(), AddressSize);
2204 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2205 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2206 const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
2207 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2208 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2209 // Ranges addresses are based on the unit's low_pc. Compute the
2210 // offset we need to apply to adapt to the the new unit's low_pc.
2211 int64_t UnitPcOffset = 0;
2212 if (OrigLowPc != -1ULL)
2213 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2214
2215 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2216 uint32_t Offset = RangeAttribute->getValue();
2217 RangeAttribute->setValue(Streamer->getRangesSectionSize());
2218 RangeList.extract(RangeExtractor, &Offset);
2219 const auto &Entries = RangeList.getEntries();
2220 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2221
2222 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2223 First.StartAddress >= CurrRange.stop()) {
2224 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2225 if (CurrRange == InvalidRange ||
2226 CurrRange.start() > First.StartAddress + OrigLowPc) {
2227 reportWarning("no mapping for range.");
2228 continue;
2229 }
2230 }
2231
2232 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2233 AddressSize);
2234 }
2235}
2236
Frederic Riss563b1b02015-03-14 03:46:51 +00002237/// \brief Generate the debug_aranges entries for \p Unit and if the
2238/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2239/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002240/// FIXME: this could actually be done right in patchRangesForUnit,
2241/// but for the sake of initial bit-for-bit compatibility with legacy
2242/// dsymutil, we have to do it in a delayed pass.
2243void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Frederic Riss563b1b02015-03-14 03:46:51 +00002244 DIEInteger *Attr = Unit.getUnitRangesAttribute();
2245 if (Attr)
Frederic Riss25440872015-03-13 23:30:31 +00002246 Attr->setValue(Streamer->getRangesSectionSize());
Frederic Riss563b1b02015-03-14 03:46:51 +00002247 Streamer->emitUnitRangesEntries(Unit, Attr != nullptr);
Frederic Riss25440872015-03-13 23:30:31 +00002248}
2249
Frederic Riss63786b02015-03-15 20:45:43 +00002250/// \brief Insert the new line info sequence \p Seq into the current
2251/// set of already linked line info \p Rows.
2252static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2253 std::vector<DWARFDebugLine::Row> &Rows) {
2254 if (Seq.empty())
2255 return;
2256
2257 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2258 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2259 Seq.clear();
2260 return;
2261 }
2262
2263 auto InsertPoint = std::lower_bound(
2264 Rows.begin(), Rows.end(), Seq.front(),
2265 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2266 return LHS.Address < RHS.Address;
2267 });
2268
2269 // FIXME: this only removes the unneeded end_sequence if the
2270 // sequences have been inserted in order. using a global sort like
2271 // described in patchLineTableForUnit() and delaying the end_sequene
2272 // elimination to emitLineTableForUnit() we can get rid of all of them.
2273 if (InsertPoint != Rows.end() &&
2274 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2275 *InsertPoint = Seq.front();
2276 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2277 } else {
2278 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2279 }
2280
2281 Seq.clear();
2282}
2283
2284/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2285/// recreate a relocated version of these for the address ranges that
2286/// are present in the binary.
2287void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2288 DWARFContext &OrigDwarf) {
2289 const DWARFDebugInfoEntryMinimal *CUDie =
2290 Unit.getOrigUnit().getCompileUnitDIE();
2291 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2292 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2293 if (StmtList == -1ULL)
2294 return;
2295
2296 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2297 if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
2298 const auto &Abbrev = OutputDIE->getAbbrev().getData();
2299 auto Stmt = std::find_if(
2300 Abbrev.begin(), Abbrev.end(), [](const DIEAbbrevData &AbbrevData) {
2301 return AbbrevData.getAttribute() == dwarf::DW_AT_stmt_list;
2302 });
2303 assert(Stmt < Abbrev.end() && "Didn't find DW_AT_stmt_list in cloned DIE!");
2304 DIEInteger *StmtAttr =
2305 cast<DIEInteger>(OutputDIE->getValues()[Stmt - Abbrev.begin()]);
2306 StmtAttr->setValue(Streamer->getLineSectionSize());
2307 }
2308
2309 // Parse the original line info for the unit.
2310 DWARFDebugLine::LineTable LineTable;
2311 uint32_t StmtOffset = StmtList;
2312 StringRef LineData = OrigDwarf.getLineSection().Data;
2313 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2314 Unit.getOrigUnit().getAddressByteSize());
2315 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2316 &StmtOffset);
2317
2318 // This vector is the output line table.
2319 std::vector<DWARFDebugLine::Row> NewRows;
2320 NewRows.reserve(LineTable.Rows.size());
2321
2322 // Current sequence of rows being extracted, before being inserted
2323 // in NewRows.
2324 std::vector<DWARFDebugLine::Row> Seq;
2325 const auto &FunctionRanges = Unit.getFunctionRanges();
2326 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2327
2328 // FIXME: This logic is meant to generate exactly the same output as
2329 // Darwin's classic dsynutil. There is a nicer way to implement this
2330 // by simply putting all the relocated line info in NewRows and simply
2331 // sorting NewRows before passing it to emitLineTableForUnit. This
2332 // should be correct as sequences for a function should stay
2333 // together in the sorted output. There are a few corner cases that
2334 // look suspicious though, and that required to implement the logic
2335 // this way. Revisit that once initial validation is finished.
2336
2337 // Iterate over the object file line info and extract the sequences
2338 // that correspond to linked functions.
2339 for (auto &Row : LineTable.Rows) {
2340 // Check wether we stepped out of the range. The range is
2341 // half-open, but consider accept the end address of the range if
2342 // it is marked as end_sequence in the input (because in that
2343 // case, the relocation offset is accurate and that entry won't
2344 // serve as the start of another function).
2345 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2346 Row.Address > CurrRange.stop() ||
2347 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2348 // We just stepped out of a known range. Insert a end_sequence
2349 // corresponding to the end of the range.
2350 uint64_t StopAddress = CurrRange != InvalidRange
2351 ? CurrRange.stop() + CurrRange.value()
2352 : -1ULL;
2353 CurrRange = FunctionRanges.find(Row.Address);
2354 bool CurrRangeValid =
2355 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2356 if (!CurrRangeValid) {
2357 CurrRange = InvalidRange;
2358 if (StopAddress != -1ULL) {
2359 // Try harder by looking in the DebugMapObject function
2360 // ranges map. There are corner cases where this finds a
2361 // valid entry. It's unclear if this is right or wrong, but
2362 // for now do as dsymutil.
2363 // FIXME: Understand exactly what cases this addresses and
2364 // potentially remove it along with the Ranges map.
2365 auto Range = Ranges.lower_bound(Row.Address);
2366 if (Range != Ranges.begin() && Range != Ranges.end())
2367 --Range;
2368
2369 if (Range != Ranges.end() && Range->first <= Row.Address &&
2370 Range->second.first >= Row.Address) {
2371 StopAddress = Row.Address + Range->second.second;
2372 }
2373 }
2374 }
2375 if (StopAddress != -1ULL && !Seq.empty()) {
2376 // Insert end sequence row with the computed end address, but
2377 // the same line as the previous one.
2378 Seq.emplace_back(Seq.back());
2379 Seq.back().Address = StopAddress;
2380 Seq.back().EndSequence = 1;
2381 Seq.back().PrologueEnd = 0;
2382 Seq.back().BasicBlock = 0;
2383 Seq.back().EpilogueBegin = 0;
2384 insertLineSequence(Seq, NewRows);
2385 }
2386
2387 if (!CurrRangeValid)
2388 continue;
2389 }
2390
2391 // Ignore empty sequences.
2392 if (Row.EndSequence && Seq.empty())
2393 continue;
2394
2395 // Relocate row address and add it to the current sequence.
2396 Row.Address += CurrRange.value();
2397 Seq.emplace_back(Row);
2398
2399 if (Row.EndSequence)
2400 insertLineSequence(Seq, NewRows);
2401 }
2402
2403 // Finished extracting, now emit the line tables.
2404 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2405 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2406 // prologue over and that works because we act as both producer and
2407 // consumer. It would be nicer to have a real configurable line
2408 // table emitter.
2409 if (LineTable.Prologue.Version != 2 ||
2410 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2411 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2412 LineTable.Prologue.OpcodeBase != 13)
2413 reportWarning("line table paramters mismatch. Cannot emit.");
2414 else
2415 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2416 LineTable.Prologue.MinInstLength, NewRows,
2417 Unit.getOrigUnit().getAddressByteSize());
2418}
2419
Frederic Rissbce93ff2015-03-16 02:05:10 +00002420void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2421 Streamer->emitPubNamesForUnit(Unit);
2422 Streamer->emitPubTypesForUnit(Unit);
2423}
2424
Frederic Rissd3455182015-01-28 18:27:01 +00002425bool DwarfLinker::link(const DebugMap &Map) {
2426
2427 if (Map.begin() == Map.end()) {
2428 errs() << "Empty debug map.\n";
2429 return false;
2430 }
2431
Frederic Rissc99ea202015-02-28 00:29:11 +00002432 if (!createStreamer(Map.getTriple(), OutputFilename))
2433 return false;
2434
Frederic Rissb8b43d52015-03-04 22:07:44 +00002435 // Size of the DIEs (and headers) generated for the linked output.
2436 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002437 // A unique ID that identifies each compile unit.
2438 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002439 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002440 CurrentDebugObject = Obj.get();
2441
Frederic Rissb9818322015-02-28 00:29:07 +00002442 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002443 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2444 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2445 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002446 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00002447 continue;
2448 }
2449
Frederic Riss1036e642015-02-13 23:18:22 +00002450 // Look for relocations that correspond to debug map entries.
2451 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002452 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002453 outs() << "No valid relocations found. Skipping.\n";
2454 continue;
2455 }
2456
Frederic Riss563cba62015-01-28 22:15:14 +00002457 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002458 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002459 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002460
Frederic Riss563cba62015-01-28 22:15:14 +00002461 // In a first phase, just read in the debug info and store the DIE
2462 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002463 for (const auto &CU : DwarfContext.compile_units()) {
2464 auto *CUDie = CU->getCompileUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002465 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002466 outs() << "Input compilation unit:";
2467 CUDie->dump(outs(), CU.get(), 0);
2468 }
Frederic Riss3cced052015-03-14 03:46:40 +00002469 Units.emplace_back(*CU, UnitID++);
Frederic Riss9aa725b2015-02-13 23:18:31 +00002470 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00002471 }
Frederic Riss563cba62015-01-28 22:15:14 +00002472
Frederic Riss84c09a52015-02-13 23:18:34 +00002473 // Then mark all the DIEs that need to be present in the linked
2474 // output and collect some information about them. Note that this
2475 // loop can not be merged with the previous one becaue cross-cu
2476 // references require the ParentIdx to be setup for every CU in
2477 // the object file before calling this.
2478 for (auto &CurrentUnit : Units)
2479 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
2480 CurrentUnit, 0);
2481
Frederic Riss23e20e92015-03-07 01:25:09 +00002482 // The calls to applyValidRelocs inside cloneDIE will walk the
2483 // reloc array again (in the same way findValidRelocsInDebugInfo()
2484 // did). We need to reset the NextValidReloc index to the beginning.
2485 NextValidReloc = 0;
2486
Frederic Rissb8b43d52015-03-04 22:07:44 +00002487 // Construct the output DIE tree by cloning the DIEs we chose to
2488 // keep above. If there are no valid relocs, then there's nothing
2489 // to clone/emit.
2490 if (!ValidRelocs.empty())
2491 for (auto &CurrentUnit : Units) {
2492 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00002493 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00002494 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2495 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002496 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00002497 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00002498 if (Options.NoOutput)
2499 continue;
2500 // FIXME: for compatibility with the classic dsymutil, we emit
2501 // an empty line table for the unit, even if the unit doesn't
2502 // actually exist in the DIE tree.
2503 patchLineTableForUnit(CurrentUnit, DwarfContext);
2504 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00002505 continue;
2506 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00002507 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002508 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002509 }
2510
2511 // Emit all the compile unit's debug information.
2512 if (!ValidRelocs.empty() && !Options.NoOutput)
2513 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00002514 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00002515 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002516 Streamer->emitCompileUnitHeader(CurrentUnit);
2517 if (!CurrentUnit.getOutputUnitDIE())
2518 continue;
2519 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2520 }
2521
Frederic Riss563cba62015-01-28 22:15:14 +00002522 // Clean-up before starting working on the next object.
2523 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00002524 }
2525
Frederic Rissb8b43d52015-03-04 22:07:44 +00002526 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00002527 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002528 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00002529 Streamer->emitStrings(StringPool);
2530 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002531
Frederic Rissc99ea202015-02-28 00:29:11 +00002532 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00002533}
2534}
Frederic Rissd3455182015-01-28 18:27:01 +00002535
Frederic Rissb9818322015-02-28 00:29:07 +00002536bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2537 const LinkOptions &Options) {
2538 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00002539 return Linker.link(DM);
2540}
2541}
Frederic Riss231f7142014-12-12 17:31:24 +00002542}