blob: 4a47405782400f6fcb860be4428fc122ef861eb2 [file] [log] [blame]
Frederic Riss231f7142014-12-12 17:31:24 +00001//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "DebugMap.h"
Frederic Rissd3455182015-01-28 18:27:01 +000010#include "BinaryHolder.h"
11#include "DebugMap.h"
Frederic Riss231f7142014-12-12 17:31:24 +000012#include "dsymutil.h"
Frederic Riss1af75f72015-03-12 18:45:10 +000013#include "llvm/ADT/IntervalMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000014#include "llvm/ADT/StringMap.h"
15#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000016#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000017#include "llvm/CodeGen/DIE.h"
Zachary Turner82af9432015-01-30 18:07:45 +000018#include "llvm/DebugInfo/DWARF/DWARFContext.h"
19#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000020#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000021#include "llvm/MC/MCAsmBackend.h"
22#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCCodeEmitter.h"
25#include "llvm/MC/MCInstrInfo.h"
26#include "llvm/MC/MCObjectFileInfo.h"
27#include "llvm/MC/MCRegisterInfo.h"
28#include "llvm/MC/MCStreamer.h"
Frederic Riss1036e642015-02-13 23:18:22 +000029#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000030#include "llvm/Support/Dwarf.h"
31#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000032#include "llvm/Support/TargetRegistry.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000035#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000036#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000037
38namespace llvm {
39namespace dsymutil {
40
Frederic Rissd3455182015-01-28 18:27:01 +000041namespace {
42
Frederic Rissdef4fb72015-02-28 00:29:01 +000043void warn(const Twine &Warning, const Twine &Context) {
44 errs() << Twine("while processing ") + Context + ":\n";
45 errs() << Twine("warning: ") + Warning + "\n";
46}
47
Frederic Rissc99ea202015-02-28 00:29:11 +000048bool error(const Twine &Error, const Twine &Context) {
49 errs() << Twine("while processing ") + Context + ":\n";
50 errs() << Twine("error: ") + Error + "\n";
51 return false;
52}
53
Frederic Riss1af75f72015-03-12 18:45:10 +000054template <typename KeyT, typename ValT>
55using HalfOpenIntervalMap =
56 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
57 IntervalMapHalfOpenInfo<KeyT>>;
58
Frederic Riss25440872015-03-13 23:30:31 +000059typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
60
Frederic Riss563cba62015-01-28 22:15:14 +000061/// \brief Stores all information relating to a compile unit, be it in
62/// its original instance in the object file to its brand new cloned
63/// and linked DIE tree.
64class CompileUnit {
65public:
66 /// \brief Information gathered about a DIE in the object file.
67 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +000068 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss9833de62015-03-06 23:22:53 +000069 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +000070 uint32_t ParentIdx; ///< The index of this DIE's parent.
71 bool Keep; ///< Is the DIE part of the linked output?
72 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +000073 };
74
Frederic Riss3cced052015-03-14 03:46:40 +000075 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
76 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Frederic Riss25440872015-03-13 23:30:31 +000077 Ranges(RangeAlloc), UnitRangeAttribute(nullptr) {
Frederic Riss563cba62015-01-28 22:15:14 +000078 Info.resize(OrigUnit.getNumDIEs());
79 }
80
Frederic Riss2838f9e2015-03-05 05:29:05 +000081 CompileUnit(CompileUnit &&RHS)
82 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
83 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +000084 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
85 // The CompileUnit container has been 'reserve()'d with the right
86 // size. We cannot move the IntervalMap anyway.
87 llvm_unreachable("CompileUnits should not be moved.");
88 }
David Blaikiea8adc132015-03-04 22:20:52 +000089
Frederic Rissc3349d42015-02-13 23:18:27 +000090 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +000091
Frederic Riss3cced052015-03-14 03:46:40 +000092 unsigned getUniqueID() const { return ID; }
93
Frederic Rissb8b43d52015-03-04 22:07:44 +000094 DIE *getOutputUnitDIE() const { return CUDie.get(); }
95 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
96
Frederic Riss563cba62015-01-28 22:15:14 +000097 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
98 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
99
Frederic Rissb8b43d52015-03-04 22:07:44 +0000100 uint64_t getStartOffset() const { return StartOffset; }
101 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000102 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000103
Frederic Riss5a62dc32015-03-13 18:35:54 +0000104 uint64_t getLowPc() const { return LowPc; }
105 uint64_t getHighPc() const { return HighPc; }
106
Frederic Riss25440872015-03-13 23:30:31 +0000107 DIEInteger *getUnitRangesAttribute() const { return UnitRangeAttribute; }
108 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
109 const std::vector<DIEInteger *> &getRangesAttributes() const {
110 return RangeAttributes;
111 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000112
113 /// \brief Compute the end offset for this unit. Must be
114 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000115 /// \returns the next unit offset (which is also the current
116 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000117 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000118
Frederic Riss6afcfce2015-03-13 18:35:57 +0000119 /// \brief Keep track of a forward reference to DIE \p Die in \p
120 /// RefUnit by \p Attr. The attribute should be fixed up later to
121 /// point to the absolute offset of \p Die in the debug_info section.
122 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
123 DIEInteger *Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000124
125 /// \brief Apply all fixups recored by noteForwardReference().
126 void fixupForwardReferences();
127
Frederic Riss1af75f72015-03-12 18:45:10 +0000128 /// \brief Add a function range [\p LowPC, \p HighPC) that is
129 /// relocatad by applying offset \p PCOffset.
130 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
131
Frederic Riss5c9c7062015-03-13 23:55:29 +0000132 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000133 /// patch up later.
134 void noteRangeAttribute(const DIE &Die, DIEInteger *Attr);
135
Frederic Riss563cba62015-01-28 22:15:14 +0000136private:
137 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000138 unsigned ID;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000139 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
140 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
141
142 uint64_t StartOffset;
143 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000144
Frederic Riss5a62dc32015-03-13 18:35:54 +0000145 uint64_t LowPc;
146 uint64_t HighPc;
147
Frederic Riss9833de62015-03-06 23:22:53 +0000148 /// \brief A list of attributes to fixup with the absolute offset of
149 /// a DIE in the debug_info section.
150 ///
151 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000152 /// cloning because for cross-cu forward refences the target DIE's
153 /// offset isn't known you emit the reference attribute.
154 std::vector<std::tuple<DIE *, const CompileUnit *, DIEInteger *>>
155 ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000156
Frederic Riss25440872015-03-13 23:30:31 +0000157 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000158 /// \brief The ranges in that interval map are the PC ranges for
159 /// functions in this unit, associated with the PC offset to apply
160 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000161 FunctionIntervals Ranges;
162
163 /// \brief DW_AT_ranges attributes to patch after we have gathered
164 /// all the unit's function addresses.
165 /// @{
166 std::vector<DIEInteger *> RangeAttributes;
167 DIEInteger *UnitRangeAttribute;
168 /// @}
Frederic Riss563cba62015-01-28 22:15:14 +0000169};
170
Frederic Riss9d441b62015-03-06 23:22:50 +0000171uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000172 NextUnitOffset = StartOffset + 11 /* Header size */;
173 // The root DIE might be null, meaning that the Unit had nothing to
174 // contribute to the linked output. In that case, we will emit the
175 // unit header without any actual DIE.
176 if (CUDie)
177 NextUnitOffset += CUDie->getSize();
178 return NextUnitOffset;
179}
180
Frederic Riss6afcfce2015-03-13 18:35:57 +0000181/// \brief Keep track of a forward cross-cu reference from this unit
182/// to \p Die that lives in \p RefUnit.
183void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
184 DIEInteger *Attr) {
185 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000186}
187
188/// \brief Apply all fixups recorded by noteForwardReference().
189void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000190 for (const auto &Ref : ForwardDIEReferences) {
191 DIE *RefDie;
192 const CompileUnit *RefUnit;
193 DIEInteger *Attr;
194 std::tie(RefDie, RefUnit, Attr) = Ref;
195 Attr->setValue(RefDie->getOffset() + RefUnit->getStartOffset());
196 }
Frederic Riss9833de62015-03-06 23:22:53 +0000197}
198
Frederic Riss5a62dc32015-03-13 18:35:54 +0000199void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
200 int64_t PcOffset) {
201 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
202 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
203 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000204}
205
Frederic Riss25440872015-03-13 23:30:31 +0000206void CompileUnit::noteRangeAttribute(const DIE &Die, DIEInteger *Attr) {
207 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
208 RangeAttributes.push_back(Attr);
209 else
210 UnitRangeAttribute = Attr;
211}
212
Frederic Rissef648462015-03-06 17:56:30 +0000213/// \brief A string table that doesn't need relocations.
214///
215/// We are doing a final link, no need for a string table that
216/// has relocation entries for every reference to it. This class
217/// provides this ablitity by just associating offsets with
218/// strings.
219class NonRelocatableStringpool {
220public:
221 /// \brief Entries are stored into the StringMap and simply linked
222 /// together through the second element of this pair in order to
223 /// keep track of insertion order.
224 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
225 MapTy;
226
227 NonRelocatableStringpool()
228 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
229 // Legacy dsymutil puts an empty string at the start of the line
230 // table.
231 getStringOffset("");
232 }
233
234 /// \brief Get the offset of string \p S in the string table. This
235 /// can insert a new element or return the offset of a preexisitng
236 /// one.
237 uint32_t getStringOffset(StringRef S);
238
239 /// \brief Get permanent storage for \p S (but do not necessarily
240 /// emit \p S in the output section).
241 /// \returns The StringRef that points to permanent storage to use
242 /// in place of \p S.
243 StringRef internString(StringRef S);
244
245 // \brief Return the first entry of the string table.
246 const MapTy::MapEntryTy *getFirstEntry() const {
247 return getNextEntry(&Sentinel);
248 }
249
250 // \brief Get the entry following \p E in the string table or null
251 // if \p E was the last entry.
252 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
253 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
254 }
255
256 uint64_t getSize() { return CurrentEndOffset; }
257
258private:
259 MapTy Strings;
260 uint32_t CurrentEndOffset;
261 MapTy::MapEntryTy Sentinel, *Last;
262};
263
264/// \brief Get the offset of string \p S in the string table. This
265/// can insert a new element or return the offset of a preexisitng
266/// one.
267uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
268 if (S.empty() && !Strings.empty())
269 return 0;
270
271 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
272 MapTy::iterator It;
273 bool Inserted;
274
275 // A non-empty string can't be at offset 0, so if we have an entry
276 // with a 0 offset, it must be a previously interned string.
277 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
278 if (Inserted || It->getValue().first == 0) {
279 // Set offset and chain at the end of the entries list.
280 It->getValue().first = CurrentEndOffset;
281 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
282 Last->getValue().second = &*It;
283 Last = &*It;
284 }
285 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000286}
Frederic Rissef648462015-03-06 17:56:30 +0000287
288/// \brief Put \p S into the StringMap so that it gets permanent
289/// storage, but do not actually link it in the chain of elements
290/// that go into the output section. A latter call to
291/// getStringOffset() with the same string will chain it though.
292StringRef NonRelocatableStringpool::internString(StringRef S) {
293 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
294 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
295 return InsertResult.first->getKey();
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000296}
Frederic Rissef648462015-03-06 17:56:30 +0000297
Frederic Rissc99ea202015-02-28 00:29:11 +0000298/// \brief The Dwarf streaming logic
299///
300/// All interactions with the MC layer that is used to build the debug
301/// information binary representation are handled in this class.
302class DwarfStreamer {
303 /// \defgroup MCObjects MC layer objects constructed by the streamer
304 /// @{
305 std::unique_ptr<MCRegisterInfo> MRI;
306 std::unique_ptr<MCAsmInfo> MAI;
307 std::unique_ptr<MCObjectFileInfo> MOFI;
308 std::unique_ptr<MCContext> MC;
309 MCAsmBackend *MAB; // Owned by MCStreamer
310 std::unique_ptr<MCInstrInfo> MII;
311 std::unique_ptr<MCSubtargetInfo> MSTI;
312 MCCodeEmitter *MCE; // Owned by MCStreamer
313 MCStreamer *MS; // Owned by AsmPrinter
314 std::unique_ptr<TargetMachine> TM;
315 std::unique_ptr<AsmPrinter> Asm;
316 /// @}
317
318 /// \brief the file we stream the linked Dwarf to.
319 std::unique_ptr<raw_fd_ostream> OutFile;
320
Frederic Riss25440872015-03-13 23:30:31 +0000321 uint32_t RangesSectionSize;
322
Frederic Rissc99ea202015-02-28 00:29:11 +0000323public:
324 /// \brief Actually create the streamer and the ouptut file.
325 ///
326 /// This could be done directly in the constructor, but it feels
327 /// more natural to handle errors through return value.
328 bool init(Triple TheTriple, StringRef OutputFilename);
329
Frederic Rissb8b43d52015-03-04 22:07:44 +0000330 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000331 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000332
333 AsmPrinter &getAsmPrinter() const { return *Asm; }
334
335 /// \brief Set the current output section to debug_info and change
336 /// the MC Dwarf version to \p DwarfVersion.
337 void switchToDebugInfoSection(unsigned DwarfVersion);
338
339 /// \brief Emit the compilation unit header for \p Unit in the
340 /// debug_info section.
341 ///
342 /// As a side effect, this also switches the current Dwarf version
343 /// of the MC layer to the one of U.getOrigUnit().
344 void emitCompileUnitHeader(CompileUnit &Unit);
345
346 /// \brief Recursively emit the DIE tree rooted at \p Die.
347 void emitDIE(DIE &Die);
348
349 /// \brief Emit the abbreviation table \p Abbrevs to the
350 /// debug_abbrev section.
351 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000352
353 /// \brief Emit the string table described by \p Pool.
354 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000355
356 /// \brief Emit debug_ranges for \p FuncRange by translating the
357 /// original \p Entries.
358 void emitRangesEntries(
359 int64_t UnitPcOffset, uint64_t OrigLowPc,
360 FunctionIntervals::const_iterator FuncRange,
361 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
362 unsigned AddressSize);
363
364 /// \brief Emit debug_ranges entries for a DW_TAG_compile_unit's DW_AT_ranges.
365 void emitUnitRangesEntries(CompileUnit &Unit);
366
367 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000368};
369
370bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
371 std::string ErrorStr;
372 std::string TripleName;
373 StringRef Context = "dwarf streamer init";
374
375 // Get the target.
376 const Target *TheTarget =
377 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
378 if (!TheTarget)
379 return error(ErrorStr, Context);
380 TripleName = TheTriple.getTriple();
381
382 // Create all the MC Objects.
383 MRI.reset(TheTarget->createMCRegInfo(TripleName));
384 if (!MRI)
385 return error(Twine("no register info for target ") + TripleName, Context);
386
387 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
388 if (!MAI)
389 return error("no asm info for target " + TripleName, Context);
390
391 MOFI.reset(new MCObjectFileInfo);
392 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
393 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
394 *MC);
395
396 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
397 if (!MAB)
398 return error("no asm backend for target " + TripleName, Context);
399
400 MII.reset(TheTarget->createMCInstrInfo());
401 if (!MII)
402 return error("no instr info info for target " + TripleName, Context);
403
404 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
405 if (!MSTI)
406 return error("no subtarget info for target " + TripleName, Context);
407
Eric Christopher0169e422015-03-10 22:03:14 +0000408 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000409 if (!MCE)
410 return error("no code emitter for target " + TripleName, Context);
411
412 // Create the output file.
413 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000414 OutFile =
415 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000416 if (EC)
417 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
418
419 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
420 *MSTI, false);
421 if (!MS)
422 return error("no object streamer for target " + TripleName, Context);
423
424 // Finally create the AsmPrinter we'll use to emit the DIEs.
425 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
426 if (!TM)
427 return error("no target machine for target " + TripleName, Context);
428
429 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
430 if (!Asm)
431 return error("no asm printer for target " + TripleName, Context);
432
Frederic Riss25440872015-03-13 23:30:31 +0000433 RangesSectionSize = 0;
434
Frederic Rissc99ea202015-02-28 00:29:11 +0000435 return true;
436}
437
438bool DwarfStreamer::finish() {
439 MS->Finish();
440 return true;
441}
442
Frederic Rissb8b43d52015-03-04 22:07:44 +0000443/// \brief Set the current output section to debug_info and change
444/// the MC Dwarf version to \p DwarfVersion.
445void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
446 MS->SwitchSection(MOFI->getDwarfInfoSection());
447 MC->setDwarfVersion(DwarfVersion);
448}
449
450/// \brief Emit the compilation unit header for \p Unit in the
451/// debug_info section.
452///
453/// A Dwarf scetion header is encoded as:
454/// uint32_t Unit length (omiting this field)
455/// uint16_t Version
456/// uint32_t Abbreviation table offset
457/// uint8_t Address size
458///
459/// Leading to a total of 11 bytes.
460void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
461 unsigned Version = Unit.getOrigUnit().getVersion();
462 switchToDebugInfoSection(Version);
463
464 // Emit size of content not including length itself. The size has
465 // already been computed in CompileUnit::computeOffsets(). Substract
466 // 4 to that size to account for the length field.
467 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
468 Asm->EmitInt16(Version);
469 // We share one abbreviations table across all units so it's always at the
470 // start of the section.
471 Asm->EmitInt32(0);
472 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
473}
474
475/// \brief Emit the \p Abbrevs array as the shared abbreviation table
476/// for the linked Dwarf file.
477void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
478 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
479 Asm->emitDwarfAbbrevs(Abbrevs);
480}
481
482/// \brief Recursively emit the DIE tree rooted at \p Die.
483void DwarfStreamer::emitDIE(DIE &Die) {
484 MS->SwitchSection(MOFI->getDwarfInfoSection());
485 Asm->emitDwarfDIE(Die);
486}
487
Frederic Rissef648462015-03-06 17:56:30 +0000488/// \brief Emit the debug_str section stored in \p Pool.
489void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
490 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
491 for (auto *Entry = Pool.getFirstEntry(); Entry;
492 Entry = Pool.getNextEntry(Entry))
493 Asm->OutStreamer.EmitBytes(
494 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
495}
496
Frederic Riss25440872015-03-13 23:30:31 +0000497/// \brief Emit the debug_range section contents for \p FuncRange by
498/// translating the original \p Entries. The debug_range section
499/// format is totally trivial, consisting just of pairs of address
500/// sized addresses describing the ranges.
501void DwarfStreamer::emitRangesEntries(
502 int64_t UnitPcOffset, uint64_t OrigLowPc,
503 FunctionIntervals::const_iterator FuncRange,
504 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
505 unsigned AddressSize) {
506 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
507
508 // Offset each range by the right amount.
509 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
510 for (const auto &Range : Entries) {
511 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
512 warn("unsupported base address selection operation",
513 "emitting debug_ranges");
514 break;
515 }
516 // Do not emit empty ranges.
517 if (Range.StartAddress == Range.EndAddress)
518 continue;
519
520 // All range entries should lie in the function range.
521 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
522 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
523 warn("inconsistent range data.", "emitting debug_ranges");
524 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
525 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
526 RangesSectionSize += 2 * AddressSize;
527 }
528
529 // Add the terminator entry.
530 MS->EmitIntValue(0, AddressSize);
531 MS->EmitIntValue(0, AddressSize);
532 RangesSectionSize += 2 * AddressSize;
533}
534
535/// \brief Emit the debug_range contents for a compile_unit level
536/// DW_AT_ranges attribute. Just aggregate all the ranges gathered
537/// inside that unit.
538void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit) {
539 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
540
541 // Offset each range by the right amount.
542 int64_t PcOffset = -Unit.getLowPc();
543 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
544 // Gather the ranges in a vector, so that we can simplify them. The
545 // IntervalMap will have coalesced the non-linked ranges, but here
546 // we want to coalesce the linked addresses.
547 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
548 const auto &FunctionRanges = Unit.getFunctionRanges();
549 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
550 Range != End; ++Range)
551 Ranges.push_back(std::make_pair(Range.start() + Range.value() + PcOffset,
552 Range.stop() + Range.value() + PcOffset));
553
554 // The object addresses where sorted, but again, the linked
555 // addresses might end up in a different order.
556 std::sort(Ranges.begin(), Ranges.end());
557
558 // Emit coalesced ranges.
559 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
560 MS->EmitIntValue(Range->first, AddressSize);
561 while (Range + 1 != End && Range->second == (Range + 1)->first)
562 ++Range;
563 MS->EmitIntValue(Range->second, AddressSize);
564 RangesSectionSize += 2 * AddressSize;
565 }
566
567 // Add the terminator entry.
568 MS->EmitIntValue(0, AddressSize);
569 MS->EmitIntValue(0, AddressSize);
570 RangesSectionSize += 2 * AddressSize;
571}
572
Frederic Rissd3455182015-01-28 18:27:01 +0000573/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000574///
575/// The link of the dwarf information from the object files will be
576/// driven by the selection of 'root DIEs', which are DIEs that
577/// describe variables or functions that are present in the linked
578/// binary (and thus have entries in the debug map). All the debug
579/// information that will be linked (the DIEs, but also the line
580/// tables, ranges, ...) is derived from that set of root DIEs.
581///
582/// The root DIEs are identified because they contain relocations that
583/// correspond to a debug map entry at specific places (the low_pc for
584/// a function, the location for a variable). These relocations are
585/// called ValidRelocs in the DwarfLinker and are gathered as a very
586/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +0000587class DwarfLinker {
588public:
Frederic Rissb9818322015-02-28 00:29:07 +0000589 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
590 : OutputFilename(OutputFilename), Options(Options),
591 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +0000592
Frederic Rissb8b43d52015-03-04 22:07:44 +0000593 ~DwarfLinker() {
594 for (auto *Abbrev : Abbreviations)
595 delete Abbrev;
596 }
597
Frederic Rissd3455182015-01-28 18:27:01 +0000598 /// \brief Link the contents of the DebugMap.
599 bool link(const DebugMap &);
600
601private:
Frederic Riss563cba62015-01-28 22:15:14 +0000602 /// \brief Called at the start of a debug object link.
603 void startDebugObject(DWARFContext &);
604
605 /// \brief Called at the end of a debug object link.
606 void endDebugObject();
607
Frederic Riss1036e642015-02-13 23:18:22 +0000608 /// \defgroup FindValidRelocations Translate debug map into a list
609 /// of relevant relocations
610 ///
611 /// @{
612 struct ValidReloc {
613 uint32_t Offset;
614 uint32_t Size;
615 uint64_t Addend;
616 const DebugMapObject::DebugMapEntry *Mapping;
617
618 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
619 const DebugMapObject::DebugMapEntry *Mapping)
620 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
621
622 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
623 };
624
625 /// \brief The valid relocations for the current DebugMapObject.
626 /// This vector is sorted by relocation offset.
627 std::vector<ValidReloc> ValidRelocs;
628
629 /// \brief Index into ValidRelocs of the next relocation to
630 /// consider. As we walk the DIEs in acsending file offset and as
631 /// ValidRelocs is sorted by file offset, keeping this index
632 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +0000633 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +0000634 unsigned NextValidReloc;
635
636 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
637 const DebugMapObject &DMO);
638
639 bool findValidRelocs(const object::SectionRef &Section,
640 const object::ObjectFile &Obj,
641 const DebugMapObject &DMO);
642
643 void findValidRelocsMachO(const object::SectionRef &Section,
644 const object::MachOObjectFile &Obj,
645 const DebugMapObject &DMO);
646 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +0000647
Frederic Riss84c09a52015-02-13 23:18:34 +0000648 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
649 ///
650 /// @{
651 /// \brief Recursively walk the \p DIE tree and look for DIEs to
652 /// keep. Store that information in \p CU's DIEInfo.
653 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
654 const DebugMapObject &DMO, CompileUnit &CU,
655 unsigned Flags);
656
657 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
658 enum TravesalFlags {
659 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
660 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
661 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
662 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
663 };
664
665 /// \brief Mark the passed DIE as well as all the ones it depends on
666 /// as kept.
667 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
668 CompileUnit::DIEInfo &MyInfo,
669 const DebugMapObject &DMO, CompileUnit &CU,
670 unsigned Flags);
671
672 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
673 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
674 unsigned Flags);
675
676 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
677 CompileUnit &Unit,
678 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
679
680 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
681 CompileUnit &Unit,
682 CompileUnit::DIEInfo &MyInfo,
683 unsigned Flags);
684
685 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
686 CompileUnit::DIEInfo &Info);
687 /// @}
688
Frederic Rissb8b43d52015-03-04 22:07:44 +0000689 /// \defgroup Linking Methods used to link the debug information
690 ///
691 /// @{
692 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
693 /// where useless (as decided by lookForDIEsToKeep()) bits have been
694 /// stripped out and addresses have been rewritten according to the
695 /// debug map.
696 ///
697 /// \param OutOffset is the offset the cloned DIE in the output
698 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +0000699 /// \param PCOffset (while cloning a function scope) is the offset
700 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000701 ///
702 /// \returns the root of the cloned tree.
703 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +0000704 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000705
706 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
707
Frederic Riss31da3242015-03-11 18:45:52 +0000708 /// \brief Information gathered and exchanged between the various
709 /// clone*Attributes helpers about the attributes of a particular DIE.
710 struct AttributesInfo {
711 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
712 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
713
714 AttributesInfo() : OrigHighPc(0), PCOffset(0) {}
715 };
716
Frederic Rissb8b43d52015-03-04 22:07:44 +0000717 /// \brief Helper for cloneDIE.
718 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
719 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +0000720 const AttributeSpec AttrSpec, unsigned AttrSize,
721 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000722
723 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +0000724 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
725 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000726
727 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +0000728 unsigned
729 cloneDieReferenceAttribute(DIE &Die,
730 const DWARFDebugInfoEntryMinimal &InputDIE,
731 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +0000732 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000733
734 /// \brief Helper for cloneDIE.
735 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
736 const DWARFFormValue &Val, unsigned AttrSize);
737
738 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +0000739 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
740 const DWARFFormValue &Val,
741 const CompileUnit &Unit, AttributesInfo &Info);
742
743 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000744 unsigned cloneScalarAttribute(DIE &Die,
745 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +0000746 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissb8b43d52015-03-04 22:07:44 +0000747 const DWARFFormValue &Val, unsigned AttrSize);
748
Frederic Riss23e20e92015-03-07 01:25:09 +0000749 /// \brief Helper for cloneDIE.
750 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
751 bool isLittleEndian);
752
Frederic Rissb8b43d52015-03-04 22:07:44 +0000753 /// \brief Assign an abbreviation number to \p Abbrev
754 void AssignAbbrev(DIEAbbrev &Abbrev);
755
756 /// \brief FoldingSet that uniques the abbreviations.
757 FoldingSet<DIEAbbrev> AbbreviationsSet;
758 /// \brief Storage for the unique Abbreviations.
759 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
760 /// be changed to a vecot of unique_ptrs.
761 std::vector<DIEAbbrev *> Abbreviations;
762
Frederic Riss25440872015-03-13 23:30:31 +0000763 /// \brief Compute and emit debug_ranges section for \p Unit, and
764 /// patch the attributes referencing it.
765 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
766
767 /// \brief Generate and emit the DW_AT_ranges attribute for a
768 /// compile_unit if it had one.
769 void generateUnitRanges(CompileUnit &Unit) const;
770
Frederic Rissb8b43d52015-03-04 22:07:44 +0000771 /// \brief DIELoc objects that need to be destructed (but not freed!).
772 std::vector<DIELoc *> DIELocs;
773 /// \brief DIEBlock objects that need to be destructed (but not freed!).
774 std::vector<DIEBlock *> DIEBlocks;
775 /// \brief Allocator used for all the DIEValue objects.
776 BumpPtrAllocator DIEAlloc;
777 /// @}
778
Frederic Riss1b9da422015-02-13 23:18:29 +0000779 /// \defgroup Helpers Various helper methods.
780 ///
781 /// @{
782 const DWARFDebugInfoEntryMinimal *
783 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
784 const DWARFDebugInfoEntryMinimal &DIE,
785 CompileUnit *&ReferencedCU);
786
787 CompileUnit *getUnitForOffset(unsigned Offset);
788
789 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +0000790 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +0000791
792 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +0000793 /// @}
794
Frederic Riss563cba62015-01-28 22:15:14 +0000795private:
Frederic Rissd3455182015-01-28 18:27:01 +0000796 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +0000797 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +0000798 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +0000799 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +0000800
801 /// The units of the current debug map object.
802 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +0000803
804 /// The debug map object curently under consideration.
805 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +0000806
807 /// \brief The Dwarf string pool
808 NonRelocatableStringpool StringPool;
Frederic Rissd3455182015-01-28 18:27:01 +0000809};
810
Frederic Riss1b9da422015-02-13 23:18:29 +0000811/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
812/// returning our CompileUnit object instead.
813CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
814 auto CU =
815 std::upper_bound(Units.begin(), Units.end(), Offset,
816 [](uint32_t LHS, const CompileUnit &RHS) {
817 return LHS < RHS.getOrigUnit().getNextUnitOffset();
818 });
819 return CU != Units.end() ? &*CU : nullptr;
820}
821
822/// \brief Resolve the DIE attribute reference that has been
823/// extracted in \p RefValue. The resulting DIE migh be in another
824/// CompileUnit which is stored into \p ReferencedCU.
825/// \returns null if resolving fails for any reason.
826const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
827 DWARFFormValue &RefValue, const DWARFUnit &Unit,
828 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
829 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
830 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
831
832 if ((RefCU = getUnitForOffset(RefOffset)))
833 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
834 return RefDie;
835
836 reportWarning("could not find referenced DIE", &Unit, &DIE);
837 return nullptr;
838}
839
840/// \brief Report a warning to the user, optionaly including
841/// information about a specific \p DIE related to the warning.
842void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +0000843 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +0000844 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +0000845 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +0000846 Context = CurrentDebugObject->getObjectFilename();
847 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +0000848
Frederic Rissb9818322015-02-28 00:29:07 +0000849 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +0000850 return;
851
852 errs() << " in DIE:\n";
853 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
854 6 /* Indent */);
855}
856
Frederic Rissc99ea202015-02-28 00:29:11 +0000857bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
858 if (Options.NoOutput)
859 return true;
860
Frederic Rissb52cf522015-02-28 00:42:37 +0000861 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +0000862 return Streamer->init(TheTriple, OutputFilename);
863}
864
Frederic Riss563cba62015-01-28 22:15:14 +0000865/// \brief Recursive helper to gather the child->parent relationships in the
866/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +0000867static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
868 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +0000869 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
870 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
871
872 if (DIE->hasChildren())
873 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
874 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +0000875 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +0000876}
877
Frederic Riss84c09a52015-02-13 23:18:34 +0000878static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
879 switch (Tag) {
880 default:
881 return false;
882 case dwarf::DW_TAG_subprogram:
883 case dwarf::DW_TAG_lexical_block:
884 case dwarf::DW_TAG_subroutine_type:
885 case dwarf::DW_TAG_structure_type:
886 case dwarf::DW_TAG_class_type:
887 case dwarf::DW_TAG_union_type:
888 return true;
889 }
890 llvm_unreachable("Invalid Tag");
891}
892
Frederic Riss563cba62015-01-28 22:15:14 +0000893void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
894 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +0000895 NextValidReloc = 0;
Frederic Riss563cba62015-01-28 22:15:14 +0000896}
897
Frederic Riss1036e642015-02-13 23:18:22 +0000898void DwarfLinker::endDebugObject() {
899 Units.clear();
900 ValidRelocs.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000901
902 for (auto *Block : DIEBlocks)
903 Block->~DIEBlock();
904 for (auto *Loc : DIELocs)
905 Loc->~DIELoc();
906
907 DIEBlocks.clear();
908 DIELocs.clear();
909 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +0000910}
911
912/// \brief Iterate over the relocations of the given \p Section and
913/// store the ones that correspond to debug map entries into the
914/// ValidRelocs array.
915void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
916 const object::MachOObjectFile &Obj,
917 const DebugMapObject &DMO) {
918 StringRef Contents;
919 Section.getContents(Contents);
920 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
921
922 for (const object::RelocationRef &Reloc : Section.relocations()) {
923 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
924 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
925 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
926 uint64_t Offset64;
927 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +0000928 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +0000929 continue;
930 }
931 uint32_t Offset = Offset64;
932 // Mach-o uses REL relocations, the addend is at the relocation offset.
933 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
934
935 auto Sym = Reloc.getSymbol();
936 if (Sym != Obj.symbol_end()) {
937 StringRef SymbolName;
938 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +0000939 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +0000940 continue;
941 }
942 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
943 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
944 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
945 // Do not store the addend. The addend was the address of the
946 // symbol in the object file, the address in the binary that is
947 // stored in the debug map doesn't need to be offseted.
948 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
949 }
950 }
951}
952
953/// \brief Dispatch the valid relocation finding logic to the
954/// appropriate handler depending on the object file format.
955bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
956 const object::ObjectFile &Obj,
957 const DebugMapObject &DMO) {
958 // Dispatch to the right handler depending on the file type.
959 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
960 findValidRelocsMachO(Section, *MachOObj, DMO);
961 else
Frederic Riss1b9da422015-02-13 23:18:29 +0000962 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +0000963
964 if (ValidRelocs.empty())
965 return false;
966
967 // Sort the relocations by offset. We will walk the DIEs linearly in
968 // the file, this allows us to just keep an index in the relocation
969 // array that we advance during our walk, rather than resorting to
970 // some associative container. See DwarfLinker::NextValidReloc.
971 std::sort(ValidRelocs.begin(), ValidRelocs.end());
972 return true;
973}
974
975/// \brief Look for relocations in the debug_info section that match
976/// entries in the debug map. These relocations will drive the Dwarf
977/// link by indicating which DIEs refer to symbols present in the
978/// linked binary.
979/// \returns wether there are any valid relocations in the debug info.
980bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
981 const DebugMapObject &DMO) {
982 // Find the debug_info section.
983 for (const object::SectionRef &Section : Obj.sections()) {
984 StringRef SectionName;
985 Section.getName(SectionName);
986 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
987 if (SectionName != "debug_info")
988 continue;
989 return findValidRelocs(Section, Obj, DMO);
990 }
991 return false;
992}
Frederic Riss563cba62015-01-28 22:15:14 +0000993
Frederic Riss84c09a52015-02-13 23:18:34 +0000994/// \brief Checks that there is a relocation against an actual debug
995/// map entry between \p StartOffset and \p NextOffset.
996///
997/// This function must be called with offsets in strictly ascending
998/// order because it never looks back at relocations it already 'went past'.
999/// \returns true and sets Info.InDebugMap if it is the case.
1000bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1001 CompileUnit::DIEInfo &Info) {
1002 assert(NextValidReloc == 0 ||
1003 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1004 if (NextValidReloc >= ValidRelocs.size())
1005 return false;
1006
1007 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1008
1009 // We might need to skip some relocs that we didn't consider. For
1010 // example the high_pc of a discarded DIE might contain a reloc that
1011 // is in the list because it actually corresponds to the start of a
1012 // function that is in the debug map.
1013 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1014 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1015
1016 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1017 return false;
1018
1019 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +00001020 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001021 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1022 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1023 ValidReloc.Mapping->getValue().ObjectAddress,
1024 ValidReloc.Mapping->getValue().BinaryAddress);
1025
Frederic Riss31da3242015-03-11 18:45:52 +00001026 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1027 ValidReloc.Addend -
1028 ValidReloc.Mapping->getValue().ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001029 Info.InDebugMap = true;
1030 return true;
1031}
1032
1033/// \brief Get the starting and ending (exclusive) offset for the
1034/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1035/// supposed to point to the position of the first attribute described
1036/// by \p Abbrev.
1037/// \return [StartOffset, EndOffset) as a pair.
1038static std::pair<uint32_t, uint32_t>
1039getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1040 unsigned Offset, const DWARFUnit &Unit) {
1041 DataExtractor Data = Unit.getDebugInfoExtractor();
1042
1043 for (unsigned i = 0; i < Idx; ++i)
1044 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1045
1046 uint32_t End = Offset;
1047 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1048
1049 return std::make_pair(Offset, End);
1050}
1051
1052/// \brief Check if a variable describing DIE should be kept.
1053/// \returns updated TraversalFlags.
1054unsigned DwarfLinker::shouldKeepVariableDIE(
1055 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1056 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1057 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1058
1059 // Global variables with constant value can always be kept.
1060 if (!(Flags & TF_InFunctionScope) &&
1061 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1062 MyInfo.InDebugMap = true;
1063 return Flags | TF_Keep;
1064 }
1065
1066 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1067 if (LocationIdx == -1U)
1068 return Flags;
1069
1070 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1071 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1072 uint32_t LocationOffset, LocationEndOffset;
1073 std::tie(LocationOffset, LocationEndOffset) =
1074 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1075
1076 // See if there is a relocation to a valid debug map entry inside
1077 // this variable's location. The order is important here. We want to
1078 // always check in the variable has a valid relocation, so that the
1079 // DIEInfo is filled. However, we don't want a static variable in a
1080 // function to force us to keep the enclosing function.
1081 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1082 (Flags & TF_InFunctionScope))
1083 return Flags;
1084
Frederic Rissb9818322015-02-28 00:29:07 +00001085 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001086 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1087
1088 return Flags | TF_Keep;
1089}
1090
1091/// \brief Check if a function describing DIE should be kept.
1092/// \returns updated TraversalFlags.
1093unsigned DwarfLinker::shouldKeepSubprogramDIE(
1094 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1095 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1096 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1097
1098 Flags |= TF_InFunctionScope;
1099
1100 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1101 if (LowPcIdx == -1U)
1102 return Flags;
1103
1104 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1105 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1106 uint32_t LowPcOffset, LowPcEndOffset;
1107 std::tie(LowPcOffset, LowPcEndOffset) =
1108 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1109
1110 uint64_t LowPc =
1111 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1112 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1113 if (LowPc == -1ULL ||
1114 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1115 return Flags;
1116
Frederic Rissb9818322015-02-28 00:29:07 +00001117 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001118 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1119
Frederic Riss1af75f72015-03-12 18:45:10 +00001120 Flags |= TF_Keep;
1121
1122 DWARFFormValue HighPcValue;
1123 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1124 reportWarning("Function without high_pc. Range will be discarded.\n",
1125 &OrigUnit, &DIE);
1126 return Flags;
1127 }
1128
1129 uint64_t HighPc;
1130 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1131 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1132 } else {
1133 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1134 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1135 }
1136
1137 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1138 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001139}
1140
1141/// \brief Check if a DIE should be kept.
1142/// \returns updated TraversalFlags.
1143unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1144 CompileUnit &Unit,
1145 CompileUnit::DIEInfo &MyInfo,
1146 unsigned Flags) {
1147 switch (DIE.getTag()) {
1148 case dwarf::DW_TAG_constant:
1149 case dwarf::DW_TAG_variable:
1150 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1151 case dwarf::DW_TAG_subprogram:
1152 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1153 case dwarf::DW_TAG_module:
1154 case dwarf::DW_TAG_imported_module:
1155 case dwarf::DW_TAG_imported_declaration:
1156 case dwarf::DW_TAG_imported_unit:
1157 // We always want to keep these.
1158 return Flags | TF_Keep;
1159 }
1160
1161 return Flags;
1162}
1163
Frederic Riss84c09a52015-02-13 23:18:34 +00001164/// \brief Mark the passed DIE as well as all the ones it depends on
1165/// as kept.
1166///
1167/// This function is called by lookForDIEsToKeep on DIEs that are
1168/// newly discovered to be needed in the link. It recursively calls
1169/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1170/// TraversalFlags to inform it that it's not doing the primary DIE
1171/// tree walk.
1172void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1173 CompileUnit::DIEInfo &MyInfo,
1174 const DebugMapObject &DMO,
1175 CompileUnit &CU, unsigned Flags) {
1176 const DWARFUnit &Unit = CU.getOrigUnit();
1177 MyInfo.Keep = true;
1178
1179 // First mark all the parent chain as kept.
1180 unsigned AncestorIdx = MyInfo.ParentIdx;
1181 while (!CU.getInfo(AncestorIdx).Keep) {
1182 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1183 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1184 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1185 }
1186
1187 // Then we need to mark all the DIEs referenced by this DIE's
1188 // attributes as kept.
1189 DataExtractor Data = Unit.getDebugInfoExtractor();
1190 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1191 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1192
1193 // Mark all DIEs referenced through atttributes as kept.
1194 for (const auto &AttrSpec : Abbrev->attributes()) {
1195 DWARFFormValue Val(AttrSpec.Form);
1196
1197 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1198 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1199 continue;
1200 }
1201
1202 Val.extractValue(Data, &Offset, &Unit);
1203 CompileUnit *ReferencedCU;
1204 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1205 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1206 TF_Keep | TF_DependencyWalk);
1207 }
1208}
1209
1210/// \brief Recursively walk the \p DIE tree and look for DIEs to
1211/// keep. Store that information in \p CU's DIEInfo.
1212///
1213/// This function is the entry point of the DIE selection
1214/// algorithm. It is expected to walk the DIE tree in file order and
1215/// (though the mediation of its helper) call hasValidRelocation() on
1216/// each DIE that might be a 'root DIE' (See DwarfLinker class
1217/// comment).
1218/// While walking the dependencies of root DIEs, this function is
1219/// also called, but during these dependency walks the file order is
1220/// not respected. The TF_DependencyWalk flag tells us which kind of
1221/// traversal we are currently doing.
1222void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1223 const DebugMapObject &DMO, CompileUnit &CU,
1224 unsigned Flags) {
1225 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1226 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1227 bool AlreadyKept = MyInfo.Keep;
1228
1229 // If the Keep flag is set, we are marking a required DIE's
1230 // dependencies. If our target is already marked as kept, we're all
1231 // set.
1232 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1233 return;
1234
1235 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1236 // because it would screw up the relocation finding logic.
1237 if (!(Flags & TF_DependencyWalk))
1238 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1239
1240 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1241 if (!AlreadyKept && (Flags & TF_Keep))
1242 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1243
1244 // The TF_ParentWalk flag tells us that we are currently walking up
1245 // the parent chain of a required DIE, and we don't want to mark all
1246 // the children of the parents as kept (consider for example a
1247 // DW_TAG_namespace node in the parent chain). There are however a
1248 // set of DIE types for which we want to ignore that directive and still
1249 // walk their children.
1250 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1251 Flags &= ~TF_ParentWalk;
1252
1253 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1254 return;
1255
1256 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1257 Child = Child->getSibling())
1258 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1259}
1260
Frederic Rissb8b43d52015-03-04 22:07:44 +00001261/// \brief Assign an abbreviation numer to \p Abbrev.
1262///
1263/// Our DIEs get freed after every DebugMapObject has been processed,
1264/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1265/// the instances hold by the DIEs. When we encounter an abbreviation
1266/// that we don't know, we create a permanent copy of it.
1267void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1268 // Check the set for priors.
1269 FoldingSetNodeID ID;
1270 Abbrev.Profile(ID);
1271 void *InsertToken;
1272 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1273
1274 // If it's newly added.
1275 if (InSet) {
1276 // Assign existing abbreviation number.
1277 Abbrev.setNumber(InSet->getNumber());
1278 } else {
1279 // Add to abbreviation list.
1280 Abbreviations.push_back(
1281 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1282 for (const auto &Attr : Abbrev.getData())
1283 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1284 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1285 // Assign the unique abbreviation number.
1286 Abbrev.setNumber(Abbreviations.size());
1287 Abbreviations.back()->setNumber(Abbreviations.size());
1288 }
1289}
1290
1291/// \brief Clone a string attribute described by \p AttrSpec and add
1292/// it to \p Die.
1293/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001294unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1295 const DWARFFormValue &Val,
1296 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001297 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001298 const char *String = *Val.getAsCString(&U);
1299 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001300 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Frederic Rissef648462015-03-06 17:56:30 +00001301 new (DIEAlloc) DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001302 return 4;
1303}
1304
1305/// \brief Clone an attribute referencing another DIE and add
1306/// it to \p Die.
1307/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001308unsigned DwarfLinker::cloneDieReferenceAttribute(
1309 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1310 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001311 CompileUnit &Unit) {
1312 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
Frederic Riss9833de62015-03-06 23:22:53 +00001313 DIE *NewRefDie = nullptr;
1314 CompileUnit *RefUnit = nullptr;
1315 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1316
1317 if (!(RefUnit = getUnitForOffset(Ref)) ||
1318 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1319 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1320 if (!AttributeString)
1321 AttributeString = "DW_AT_???";
1322 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1323 ". Dropping.",
Frederic Riss6afcfce2015-03-13 18:35:57 +00001324 &Unit.getOrigUnit(), &InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001325 return 0;
1326 }
1327
1328 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1329 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1330 if (!RefInfo.Clone) {
1331 assert(Ref > InputDIE.getOffset());
1332 // We haven't cloned this DIE yet. Just create an empty one and
1333 // store it. It'll get really cloned when we process it.
1334 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1335 }
1336 NewRefDie = RefInfo.Clone;
1337
1338 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1339 // We cannot currently rely on a DIEEntry to emit ref_addr
1340 // references, because the implementation calls back to DwarfDebug
1341 // to find the unit offset. (We don't have a DwarfDebug)
1342 // FIXME: we should be able to design DIEEntry reliance on
1343 // DwarfDebug away.
1344 DIEInteger *Attr;
1345 if (Ref < InputDIE.getOffset()) {
1346 // We must have already cloned that DIE.
1347 uint32_t NewRefOffset =
1348 RefUnit->getStartOffset() + NewRefDie->getOffset();
1349 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1350 } else {
1351 // A forward reference. Note and fixup later.
1352 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
Frederic Riss6afcfce2015-03-13 18:35:57 +00001353 Unit.noteForwardReference(NewRefDie, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +00001354 }
1355 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1356 Attr);
1357 return AttrSize;
1358 }
1359
Frederic Rissb8b43d52015-03-04 22:07:44 +00001360 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss9833de62015-03-06 23:22:53 +00001361 new (DIEAlloc) DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001362 return AttrSize;
1363}
1364
1365/// \brief Clone an attribute of block form (locations, constants) and add
1366/// it to \p Die.
1367/// \returns the size of the new attribute.
1368unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1369 const DWARFFormValue &Val,
1370 unsigned AttrSize) {
1371 DIE *Attr;
1372 DIEValue *Value;
1373 DIELoc *Loc = nullptr;
1374 DIEBlock *Block = nullptr;
1375 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001376 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001377 Loc = new (DIEAlloc) DIELoc();
1378 DIELocs.push_back(Loc);
1379 } else {
1380 Block = new (DIEAlloc) DIEBlock();
1381 DIEBlocks.push_back(Block);
1382 }
1383 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1384 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1385 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1386 for (auto Byte : Bytes)
1387 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1388 new (DIEAlloc) DIEInteger(Byte));
1389 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1390 // the DIE class, this if could be replaced by
1391 // Attr->setSize(Bytes.size()).
1392 if (Streamer) {
1393 if (Loc)
1394 Loc->ComputeSize(&Streamer->getAsmPrinter());
1395 else
1396 Block->ComputeSize(&Streamer->getAsmPrinter());
1397 }
1398 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1399 Value);
1400 return AttrSize;
1401}
1402
Frederic Riss31da3242015-03-11 18:45:52 +00001403/// \brief Clone an address attribute and add it to \p Die.
1404/// \returns the size of the new attribute.
1405unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1406 const DWARFFormValue &Val,
1407 const CompileUnit &Unit,
1408 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001409 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00001410 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1411 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1412 Die.getTag() == dwarf::DW_TAG_lexical_block)
1413 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001414 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1415 Addr = Unit.getLowPc();
1416 if (Addr == UINT64_MAX)
1417 return 0;
1418 }
Frederic Riss31da3242015-03-11 18:45:52 +00001419 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001420 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1421 if (uint64_t HighPc = Unit.getHighPc())
1422 Addr = HighPc;
1423 else
1424 return 0;
1425 } else
1426 // If we have a high_pc recorded for the input DIE, use
1427 // it. Otherwise (when no relocations where applied) just use the
1428 // one we just decoded.
1429 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00001430 }
1431
1432 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1433 static_cast<dwarf::Form>(AttrSpec.Form),
1434 new (DIEAlloc) DIEInteger(Addr));
1435 return Unit.getOrigUnit().getAddressByteSize();
1436}
1437
Frederic Rissb8b43d52015-03-04 22:07:44 +00001438/// \brief Clone a scalar attribute and add it to \p Die.
1439/// \returns the size of the new attribute.
1440unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00001441 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
1442 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001443 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001444 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1445 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1446 if (Unit.getLowPc() == -1ULL)
1447 return 0;
1448 // Dwarf >= 4 high_pc is an size, not an address.
1449 Value = Unit.getHighPc() - Unit.getLowPc();
1450 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00001451 Value = *Val.getAsSectionOffset();
1452 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1453 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001454 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1455 Value = *OptionalValue;
1456 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001457 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1458 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001459 return 0;
1460 }
Frederic Riss25440872015-03-13 23:30:31 +00001461 DIEInteger *Attr = new (DIEAlloc) DIEInteger(Value);
1462 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
1463 Unit.noteRangeAttribute(Die, Attr);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001464 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss25440872015-03-13 23:30:31 +00001465 Attr);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001466 return AttrSize;
1467}
1468
1469/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1470/// value \p Val, and add it to \p Die.
1471/// \returns the size of the cloned attribute.
1472unsigned DwarfLinker::cloneAttribute(DIE &Die,
1473 const DWARFDebugInfoEntryMinimal &InputDIE,
1474 CompileUnit &Unit,
1475 const DWARFFormValue &Val,
1476 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00001477 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001478 const DWARFUnit &U = Unit.getOrigUnit();
1479
1480 switch (AttrSpec.Form) {
1481 case dwarf::DW_FORM_strp:
1482 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00001483 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001484 case dwarf::DW_FORM_ref_addr:
1485 case dwarf::DW_FORM_ref1:
1486 case dwarf::DW_FORM_ref2:
1487 case dwarf::DW_FORM_ref4:
1488 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00001489 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001490 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001491 case dwarf::DW_FORM_block:
1492 case dwarf::DW_FORM_block1:
1493 case dwarf::DW_FORM_block2:
1494 case dwarf::DW_FORM_block4:
1495 case dwarf::DW_FORM_exprloc:
1496 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1497 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00001498 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001499 case dwarf::DW_FORM_data1:
1500 case dwarf::DW_FORM_data2:
1501 case dwarf::DW_FORM_data4:
1502 case dwarf::DW_FORM_data8:
1503 case dwarf::DW_FORM_udata:
1504 case dwarf::DW_FORM_sdata:
1505 case dwarf::DW_FORM_sec_offset:
1506 case dwarf::DW_FORM_flag:
1507 case dwarf::DW_FORM_flag_present:
Frederic Riss5a62dc32015-03-13 18:35:54 +00001508 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001509 default:
1510 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1511 &InputDIE);
1512 }
1513
1514 return 0;
1515}
1516
Frederic Riss23e20e92015-03-07 01:25:09 +00001517/// \brief Apply the valid relocations found by findValidRelocs() to
1518/// the buffer \p Data, taking into account that Data is at \p BaseOffset
1519/// in the debug_info section.
1520///
1521/// Like for findValidRelocs(), this function must be called with
1522/// monotonic \p BaseOffset values.
1523///
1524/// \returns wether any reloc has been applied.
1525bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1526 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00001527 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00001528 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1529 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00001530 if (NextValidReloc >= ValidRelocs.size())
1531 return false;
1532
1533 // Skip relocs that haven't been applied.
1534 while (NextValidReloc < ValidRelocs.size() &&
1535 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1536 ++NextValidReloc;
1537
1538 bool Applied = false;
1539 uint64_t EndOffset = BaseOffset + Data.size();
1540 while (NextValidReloc < ValidRelocs.size() &&
1541 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1542 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1543 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1544 assert(ValidReloc.Offset - BaseOffset < Data.size());
1545 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1546 char Buf[8];
1547 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1548 Value += ValidReloc.Addend;
1549 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1550 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1551 Buf[i] = uint8_t(Value >> (Index * 8));
1552 }
1553 assert(ValidReloc.Size <= sizeof(Buf));
1554 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1555 Applied = true;
1556 }
1557
1558 return Applied;
1559}
1560
Frederic Rissb8b43d52015-03-04 22:07:44 +00001561/// \brief Recursively clone \p InputDIE's subtrees that have been
1562/// selected to appear in the linked output.
1563///
1564/// \param OutOffset is the Offset where the newly created DIE will
1565/// lie in the linked compile unit.
1566///
1567/// \returns the cloned DIE object or null if nothing was selected.
1568DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00001569 CompileUnit &Unit, int64_t PCOffset,
1570 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001571 DWARFUnit &U = Unit.getOrigUnit();
1572 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001573 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001574
1575 // Should the DIE appear in the output?
1576 if (!Unit.getInfo(Idx).Keep)
1577 return nullptr;
1578
1579 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00001580 // The DIE might have been already created by a forward reference
1581 // (see cloneDieReferenceAttribute()).
1582 DIE *Die = Info.Clone;
1583 if (!Die)
1584 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1585 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00001586 Die->setOffset(OutOffset);
1587
1588 // Extract and clone every attribute.
1589 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00001590 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00001591 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00001592
1593 // We could copy the data only if we need to aply a relocation to
1594 // it. After testing, it seems there is no performance downside to
1595 // doing the copy unconditionally, and it makes the code simpler.
1596 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1597 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1598 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00001599 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1600 // If we applied relocations, we store the value of high_pc that was
1601 // potentially stored in the input DIE. If high_pc is an address
1602 // (Dwarf version == 2), then it might have been relocated to a
1603 // totally unrelated value (because the end address in the object
1604 // file might be start address of another function which got moved
1605 // independantly by the linker). The computation of the actual
1606 // high_pc value is done in cloneAddressAttribute().
1607 AttrInfo.OrigHighPc =
1608 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
1609 }
Frederic Riss23e20e92015-03-07 01:25:09 +00001610
1611 // Reset the Offset to 0 as we will be working on the local copy of
1612 // the data.
1613 Offset = 0;
1614
Frederic Rissb8b43d52015-03-04 22:07:44 +00001615 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1616 Offset += getULEB128Size(Abbrev->getCode());
1617
Frederic Riss31da3242015-03-11 18:45:52 +00001618 // We are entering a subprogram. Get and propagate the PCOffset.
1619 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1620 PCOffset = Info.AddrAdjust;
1621 AttrInfo.PCOffset = PCOffset;
1622
Frederic Rissb8b43d52015-03-04 22:07:44 +00001623 for (const auto &AttrSpec : Abbrev->attributes()) {
1624 DWARFFormValue Val(AttrSpec.Form);
1625 uint32_t AttrSize = Offset;
1626 Val.extractValue(Data, &Offset, &U);
1627 AttrSize = Offset - AttrSize;
1628
Frederic Riss31da3242015-03-11 18:45:52 +00001629 OutOffset +=
1630 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001631 }
1632
1633 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1634 // If a scope DIE is kept, we must have kept at least one child. If
1635 // it's not the case, we'll just be emitting one wasteful end of
1636 // children marker, but things won't break.
1637 if (InputDIE.hasChildren())
1638 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1639 // Assign a permanent abbrev number
1640 AssignAbbrev(Die->getAbbrev());
1641
1642 // Add the size of the abbreviation number to the output offset.
1643 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1644
1645 if (!Abbrev->hasChildren()) {
1646 // Update our size.
1647 Die->setSize(OutOffset - Die->getOffset());
1648 return Die;
1649 }
1650
1651 // Recursively clone children.
1652 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1653 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00001654 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001655 Die->addChild(std::unique_ptr<DIE>(Clone));
1656 OutOffset = Clone->getOffset() + Clone->getSize();
1657 }
1658 }
1659
1660 // Account for the end of children marker.
1661 OutOffset += sizeof(int8_t);
1662 // Update our size.
1663 Die->setSize(OutOffset - Die->getOffset());
1664 return Die;
1665}
1666
Frederic Riss25440872015-03-13 23:30:31 +00001667/// \brief Patch the input object file relevant debug_ranges entries
1668/// and emit them in the output file. Update the relevant attributes
1669/// to point at the new entries.
1670void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
1671 DWARFContext &OrigDwarf) const {
1672 DWARFDebugRangeList RangeList;
1673 const auto &FunctionRanges = Unit.getFunctionRanges();
1674 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
1675 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
1676 OrigDwarf.isLittleEndian(), AddressSize);
1677 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1678 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1679 const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
1680 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
1681 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1682 // Ranges addresses are based on the unit's low_pc. Compute the
1683 // offset we need to apply to adapt to the the new unit's low_pc.
1684 int64_t UnitPcOffset = 0;
1685 if (OrigLowPc != -1ULL)
1686 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
1687
1688 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
1689 uint32_t Offset = RangeAttribute->getValue();
1690 RangeAttribute->setValue(Streamer->getRangesSectionSize());
1691 RangeList.extract(RangeExtractor, &Offset);
1692 const auto &Entries = RangeList.getEntries();
1693 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
1694
1695 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
1696 First.StartAddress >= CurrRange.stop()) {
1697 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
1698 if (CurrRange == InvalidRange ||
1699 CurrRange.start() > First.StartAddress + OrigLowPc) {
1700 reportWarning("no mapping for range.");
1701 continue;
1702 }
1703 }
1704
1705 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
1706 AddressSize);
1707 }
1708}
1709
1710/// \brief Generate the debug_ranges entries for \p Unit's
1711/// DW_AT_ranges attribute if there is one.
1712/// FIXME: this could actually be done right in patchRangesForUnit,
1713/// but for the sake of initial bit-for-bit compatibility with legacy
1714/// dsymutil, we have to do it in a delayed pass.
1715void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
1716 if (DIEInteger *Attr = Unit.getUnitRangesAttribute()) {
1717 Attr->setValue(Streamer->getRangesSectionSize());
1718 Streamer->emitUnitRangesEntries(Unit);
1719 }
1720}
1721
Frederic Rissd3455182015-01-28 18:27:01 +00001722bool DwarfLinker::link(const DebugMap &Map) {
1723
1724 if (Map.begin() == Map.end()) {
1725 errs() << "Empty debug map.\n";
1726 return false;
1727 }
1728
Frederic Rissc99ea202015-02-28 00:29:11 +00001729 if (!createStreamer(Map.getTriple(), OutputFilename))
1730 return false;
1731
Frederic Rissb8b43d52015-03-04 22:07:44 +00001732 // Size of the DIEs (and headers) generated for the linked output.
1733 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00001734 // A unique ID that identifies each compile unit.
1735 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00001736 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001737 CurrentDebugObject = Obj.get();
1738
Frederic Rissb9818322015-02-28 00:29:07 +00001739 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00001740 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1741 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1742 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001743 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00001744 continue;
1745 }
1746
Frederic Riss1036e642015-02-13 23:18:22 +00001747 // Look for relocations that correspond to debug map entries.
1748 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00001749 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00001750 outs() << "No valid relocations found. Skipping.\n";
1751 continue;
1752 }
1753
Frederic Riss563cba62015-01-28 22:15:14 +00001754 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00001755 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss563cba62015-01-28 22:15:14 +00001756 startDebugObject(DwarfContext);
Frederic Rissd3455182015-01-28 18:27:01 +00001757
Frederic Riss563cba62015-01-28 22:15:14 +00001758 // In a first phase, just read in the debug info and store the DIE
1759 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00001760 for (const auto &CU : DwarfContext.compile_units()) {
1761 auto *CUDie = CU->getCompileUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00001762 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00001763 outs() << "Input compilation unit:";
1764 CUDie->dump(outs(), CU.get(), 0);
1765 }
Frederic Riss3cced052015-03-14 03:46:40 +00001766 Units.emplace_back(*CU, UnitID++);
Frederic Riss9aa725b2015-02-13 23:18:31 +00001767 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00001768 }
Frederic Riss563cba62015-01-28 22:15:14 +00001769
Frederic Riss84c09a52015-02-13 23:18:34 +00001770 // Then mark all the DIEs that need to be present in the linked
1771 // output and collect some information about them. Note that this
1772 // loop can not be merged with the previous one becaue cross-cu
1773 // references require the ParentIdx to be setup for every CU in
1774 // the object file before calling this.
1775 for (auto &CurrentUnit : Units)
1776 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1777 CurrentUnit, 0);
1778
Frederic Riss23e20e92015-03-07 01:25:09 +00001779 // The calls to applyValidRelocs inside cloneDIE will walk the
1780 // reloc array again (in the same way findValidRelocsInDebugInfo()
1781 // did). We need to reset the NextValidReloc index to the beginning.
1782 NextValidReloc = 0;
1783
Frederic Rissb8b43d52015-03-04 22:07:44 +00001784 // Construct the output DIE tree by cloning the DIEs we chose to
1785 // keep above. If there are no valid relocs, then there's nothing
1786 // to clone/emit.
1787 if (!ValidRelocs.empty())
1788 for (auto &CurrentUnit : Units) {
1789 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00001790 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00001791 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
1792 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001793 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00001794 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss25440872015-03-13 23:30:31 +00001795 if (!OutputDIE || Options.NoOutput)
1796 continue;
1797 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001798 }
1799
1800 // Emit all the compile unit's debug information.
1801 if (!ValidRelocs.empty() && !Options.NoOutput)
1802 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00001803 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00001804 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001805 Streamer->emitCompileUnitHeader(CurrentUnit);
1806 if (!CurrentUnit.getOutputUnitDIE())
1807 continue;
1808 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1809 }
1810
Frederic Riss563cba62015-01-28 22:15:14 +00001811 // Clean-up before starting working on the next object.
1812 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00001813 }
1814
Frederic Rissb8b43d52015-03-04 22:07:44 +00001815 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00001816 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001817 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00001818 Streamer->emitStrings(StringPool);
1819 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00001820
Frederic Rissc99ea202015-02-28 00:29:11 +00001821 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00001822}
1823}
Frederic Rissd3455182015-01-28 18:27:01 +00001824
Frederic Rissb9818322015-02-28 00:29:07 +00001825bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1826 const LinkOptions &Options) {
1827 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00001828 return Linker.link(DM);
1829}
1830}
Frederic Riss231f7142014-12-12 17:31:24 +00001831}