blob: f71a01d7c626352a9784fa974b9311363a425bb2 [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 Riss231f7142014-12-12 17:31:24 +000036
37namespace llvm {
38namespace dsymutil {
39
Frederic Rissd3455182015-01-28 18:27:01 +000040namespace {
41
Frederic Rissdef4fb72015-02-28 00:29:01 +000042void warn(const Twine &Warning, const Twine &Context) {
43 errs() << Twine("while processing ") + Context + ":\n";
44 errs() << Twine("warning: ") + Warning + "\n";
45}
46
Frederic Rissc99ea202015-02-28 00:29:11 +000047bool error(const Twine &Error, const Twine &Context) {
48 errs() << Twine("while processing ") + Context + ":\n";
49 errs() << Twine("error: ") + Error + "\n";
50 return false;
51}
52
Frederic Riss1af75f72015-03-12 18:45:10 +000053template <typename KeyT, typename ValT>
54using HalfOpenIntervalMap =
55 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
56 IntervalMapHalfOpenInfo<KeyT>>;
57
Frederic Riss563cba62015-01-28 22:15:14 +000058/// \brief Stores all information relating to a compile unit, be it in
59/// its original instance in the object file to its brand new cloned
60/// and linked DIE tree.
61class CompileUnit {
62public:
63 /// \brief Information gathered about a DIE in the object file.
64 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +000065 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss9833de62015-03-06 23:22:53 +000066 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +000067 uint32_t ParentIdx; ///< The index of this DIE's parent.
68 bool Keep; ///< Is the DIE part of the linked output?
69 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +000070 };
71
Frederic Riss1af75f72015-03-12 18:45:10 +000072 CompileUnit(DWARFUnit &OrigUnit)
73 : OrigUnit(OrigUnit), RangeAlloc(), Ranges(RangeAlloc) {
Frederic Riss563cba62015-01-28 22:15:14 +000074 Info.resize(OrigUnit.getNumDIEs());
75 }
76
Frederic Riss2838f9e2015-03-05 05:29:05 +000077 CompileUnit(CompileUnit &&RHS)
78 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
79 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +000080 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
81 // The CompileUnit container has been 'reserve()'d with the right
82 // size. We cannot move the IntervalMap anyway.
83 llvm_unreachable("CompileUnits should not be moved.");
84 }
David Blaikiea8adc132015-03-04 22:20:52 +000085
Frederic Rissc3349d42015-02-13 23:18:27 +000086 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +000087
Frederic Rissb8b43d52015-03-04 22:07:44 +000088 DIE *getOutputUnitDIE() const { return CUDie.get(); }
89 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
90
Frederic Riss563cba62015-01-28 22:15:14 +000091 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
92 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
93
Frederic Rissb8b43d52015-03-04 22:07:44 +000094 uint64_t getStartOffset() const { return StartOffset; }
95 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
96
Frederic Riss9d441b62015-03-06 23:22:50 +000097 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
98
99 /// \brief Compute the end offset for this unit. Must be
100 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000101 /// \returns the next unit offset (which is also the current
102 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000103 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000104
Frederic Riss9833de62015-03-06 23:22:53 +0000105 /// \brief Keep track of a forward reference to DIE \p Die by
106 /// \p Attr. The attribute should be fixed up later to point to the
107 /// absolute offset of \p Die in the debug_info section.
108 void noteForwardReference(DIE *Die, DIEInteger *Attr);
109
110 /// \brief Apply all fixups recored by noteForwardReference().
111 void fixupForwardReferences();
112
Frederic Riss1af75f72015-03-12 18:45:10 +0000113 /// \brief Add a function range [\p LowPC, \p HighPC) that is
114 /// relocatad by applying offset \p PCOffset.
115 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
116
Frederic Riss563cba62015-01-28 22:15:14 +0000117private:
118 DWARFUnit &OrigUnit;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000119 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
120 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
121
122 uint64_t StartOffset;
123 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000124
125 /// \brief A list of attributes to fixup with the absolute offset of
126 /// a DIE in the debug_info section.
127 ///
128 /// The offsets for the attributes in this array couldn't be set while
129 /// cloning because for forward refences the target DIE's offset isn't
130 /// known you emit the reference attribute.
131 std::vector<std::pair<DIE *, DIEInteger *>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000132
133 HalfOpenIntervalMap<uint64_t, int64_t>::Allocator RangeAlloc;
134 /// \brief The ranges in that interval map are the PC ranges for
135 /// functions in this unit, associated with the PC offset to apply
136 /// to the addresses to get the linked address.
137 HalfOpenIntervalMap<uint64_t, int64_t> Ranges;
Frederic Riss563cba62015-01-28 22:15:14 +0000138};
139
Frederic Riss9d441b62015-03-06 23:22:50 +0000140uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000141 NextUnitOffset = StartOffset + 11 /* Header size */;
142 // The root DIE might be null, meaning that the Unit had nothing to
143 // contribute to the linked output. In that case, we will emit the
144 // unit header without any actual DIE.
145 if (CUDie)
146 NextUnitOffset += CUDie->getSize();
147 return NextUnitOffset;
148}
149
Frederic Riss9833de62015-03-06 23:22:53 +0000150/// \brief Keep track of a forward reference to \p Die.
151void CompileUnit::noteForwardReference(DIE *Die, DIEInteger *Attr) {
152 ForwardDIEReferences.emplace_back(Die, Attr);
153}
154
155/// \brief Apply all fixups recorded by noteForwardReference().
156void CompileUnit::fixupForwardReferences() {
157 for (const auto &Ref : ForwardDIEReferences)
158 Ref.second->setValue(Ref.first->getOffset() + getStartOffset());
159}
160
Frederic Riss1af75f72015-03-12 18:45:10 +0000161void CompileUnit::addFunctionRange(uint64_t LowPC, uint64_t HighPC,
162 int64_t PCOffset) {
163 Ranges.insert(LowPC, HighPC, PCOffset);
164}
165
Frederic Rissef648462015-03-06 17:56:30 +0000166/// \brief A string table that doesn't need relocations.
167///
168/// We are doing a final link, no need for a string table that
169/// has relocation entries for every reference to it. This class
170/// provides this ablitity by just associating offsets with
171/// strings.
172class NonRelocatableStringpool {
173public:
174 /// \brief Entries are stored into the StringMap and simply linked
175 /// together through the second element of this pair in order to
176 /// keep track of insertion order.
177 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
178 MapTy;
179
180 NonRelocatableStringpool()
181 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
182 // Legacy dsymutil puts an empty string at the start of the line
183 // table.
184 getStringOffset("");
185 }
186
187 /// \brief Get the offset of string \p S in the string table. This
188 /// can insert a new element or return the offset of a preexisitng
189 /// one.
190 uint32_t getStringOffset(StringRef S);
191
192 /// \brief Get permanent storage for \p S (but do not necessarily
193 /// emit \p S in the output section).
194 /// \returns The StringRef that points to permanent storage to use
195 /// in place of \p S.
196 StringRef internString(StringRef S);
197
198 // \brief Return the first entry of the string table.
199 const MapTy::MapEntryTy *getFirstEntry() const {
200 return getNextEntry(&Sentinel);
201 }
202
203 // \brief Get the entry following \p E in the string table or null
204 // if \p E was the last entry.
205 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
206 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
207 }
208
209 uint64_t getSize() { return CurrentEndOffset; }
210
211private:
212 MapTy Strings;
213 uint32_t CurrentEndOffset;
214 MapTy::MapEntryTy Sentinel, *Last;
215};
216
217/// \brief Get the offset of string \p S in the string table. This
218/// can insert a new element or return the offset of a preexisitng
219/// one.
220uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
221 if (S.empty() && !Strings.empty())
222 return 0;
223
224 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
225 MapTy::iterator It;
226 bool Inserted;
227
228 // A non-empty string can't be at offset 0, so if we have an entry
229 // with a 0 offset, it must be a previously interned string.
230 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
231 if (Inserted || It->getValue().first == 0) {
232 // Set offset and chain at the end of the entries list.
233 It->getValue().first = CurrentEndOffset;
234 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
235 Last->getValue().second = &*It;
236 Last = &*It;
237 }
238 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000239}
Frederic Rissef648462015-03-06 17:56:30 +0000240
241/// \brief Put \p S into the StringMap so that it gets permanent
242/// storage, but do not actually link it in the chain of elements
243/// that go into the output section. A latter call to
244/// getStringOffset() with the same string will chain it though.
245StringRef NonRelocatableStringpool::internString(StringRef S) {
246 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
247 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
248 return InsertResult.first->getKey();
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000249}
Frederic Rissef648462015-03-06 17:56:30 +0000250
Frederic Rissc99ea202015-02-28 00:29:11 +0000251/// \brief The Dwarf streaming logic
252///
253/// All interactions with the MC layer that is used to build the debug
254/// information binary representation are handled in this class.
255class DwarfStreamer {
256 /// \defgroup MCObjects MC layer objects constructed by the streamer
257 /// @{
258 std::unique_ptr<MCRegisterInfo> MRI;
259 std::unique_ptr<MCAsmInfo> MAI;
260 std::unique_ptr<MCObjectFileInfo> MOFI;
261 std::unique_ptr<MCContext> MC;
262 MCAsmBackend *MAB; // Owned by MCStreamer
263 std::unique_ptr<MCInstrInfo> MII;
264 std::unique_ptr<MCSubtargetInfo> MSTI;
265 MCCodeEmitter *MCE; // Owned by MCStreamer
266 MCStreamer *MS; // Owned by AsmPrinter
267 std::unique_ptr<TargetMachine> TM;
268 std::unique_ptr<AsmPrinter> Asm;
269 /// @}
270
271 /// \brief the file we stream the linked Dwarf to.
272 std::unique_ptr<raw_fd_ostream> OutFile;
273
274public:
275 /// \brief Actually create the streamer and the ouptut file.
276 ///
277 /// This could be done directly in the constructor, but it feels
278 /// more natural to handle errors through return value.
279 bool init(Triple TheTriple, StringRef OutputFilename);
280
Frederic Rissb8b43d52015-03-04 22:07:44 +0000281 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000282 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000283
284 AsmPrinter &getAsmPrinter() const { return *Asm; }
285
286 /// \brief Set the current output section to debug_info and change
287 /// the MC Dwarf version to \p DwarfVersion.
288 void switchToDebugInfoSection(unsigned DwarfVersion);
289
290 /// \brief Emit the compilation unit header for \p Unit in the
291 /// debug_info section.
292 ///
293 /// As a side effect, this also switches the current Dwarf version
294 /// of the MC layer to the one of U.getOrigUnit().
295 void emitCompileUnitHeader(CompileUnit &Unit);
296
297 /// \brief Recursively emit the DIE tree rooted at \p Die.
298 void emitDIE(DIE &Die);
299
300 /// \brief Emit the abbreviation table \p Abbrevs to the
301 /// debug_abbrev section.
302 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000303
304 /// \brief Emit the string table described by \p Pool.
305 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Rissc99ea202015-02-28 00:29:11 +0000306};
307
308bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
309 std::string ErrorStr;
310 std::string TripleName;
311 StringRef Context = "dwarf streamer init";
312
313 // Get the target.
314 const Target *TheTarget =
315 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
316 if (!TheTarget)
317 return error(ErrorStr, Context);
318 TripleName = TheTriple.getTriple();
319
320 // Create all the MC Objects.
321 MRI.reset(TheTarget->createMCRegInfo(TripleName));
322 if (!MRI)
323 return error(Twine("no register info for target ") + TripleName, Context);
324
325 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
326 if (!MAI)
327 return error("no asm info for target " + TripleName, Context);
328
329 MOFI.reset(new MCObjectFileInfo);
330 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
331 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
332 *MC);
333
334 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
335 if (!MAB)
336 return error("no asm backend for target " + TripleName, Context);
337
338 MII.reset(TheTarget->createMCInstrInfo());
339 if (!MII)
340 return error("no instr info info for target " + TripleName, Context);
341
342 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
343 if (!MSTI)
344 return error("no subtarget info for target " + TripleName, Context);
345
Eric Christopher0169e422015-03-10 22:03:14 +0000346 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000347 if (!MCE)
348 return error("no code emitter for target " + TripleName, Context);
349
350 // Create the output file.
351 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000352 OutFile =
353 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000354 if (EC)
355 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
356
357 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
358 *MSTI, false);
359 if (!MS)
360 return error("no object streamer for target " + TripleName, Context);
361
362 // Finally create the AsmPrinter we'll use to emit the DIEs.
363 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
364 if (!TM)
365 return error("no target machine for target " + TripleName, Context);
366
367 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
368 if (!Asm)
369 return error("no asm printer for target " + TripleName, Context);
370
371 return true;
372}
373
374bool DwarfStreamer::finish() {
375 MS->Finish();
376 return true;
377}
378
Frederic Rissb8b43d52015-03-04 22:07:44 +0000379/// \brief Set the current output section to debug_info and change
380/// the MC Dwarf version to \p DwarfVersion.
381void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
382 MS->SwitchSection(MOFI->getDwarfInfoSection());
383 MC->setDwarfVersion(DwarfVersion);
384}
385
386/// \brief Emit the compilation unit header for \p Unit in the
387/// debug_info section.
388///
389/// A Dwarf scetion header is encoded as:
390/// uint32_t Unit length (omiting this field)
391/// uint16_t Version
392/// uint32_t Abbreviation table offset
393/// uint8_t Address size
394///
395/// Leading to a total of 11 bytes.
396void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
397 unsigned Version = Unit.getOrigUnit().getVersion();
398 switchToDebugInfoSection(Version);
399
400 // Emit size of content not including length itself. The size has
401 // already been computed in CompileUnit::computeOffsets(). Substract
402 // 4 to that size to account for the length field.
403 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
404 Asm->EmitInt16(Version);
405 // We share one abbreviations table across all units so it's always at the
406 // start of the section.
407 Asm->EmitInt32(0);
408 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
409}
410
411/// \brief Emit the \p Abbrevs array as the shared abbreviation table
412/// for the linked Dwarf file.
413void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
414 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
415 Asm->emitDwarfAbbrevs(Abbrevs);
416}
417
418/// \brief Recursively emit the DIE tree rooted at \p Die.
419void DwarfStreamer::emitDIE(DIE &Die) {
420 MS->SwitchSection(MOFI->getDwarfInfoSection());
421 Asm->emitDwarfDIE(Die);
422}
423
Frederic Rissef648462015-03-06 17:56:30 +0000424/// \brief Emit the debug_str section stored in \p Pool.
425void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
426 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
427 for (auto *Entry = Pool.getFirstEntry(); Entry;
428 Entry = Pool.getNextEntry(Entry))
429 Asm->OutStreamer.EmitBytes(
430 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
431}
432
Frederic Rissd3455182015-01-28 18:27:01 +0000433/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000434///
435/// The link of the dwarf information from the object files will be
436/// driven by the selection of 'root DIEs', which are DIEs that
437/// describe variables or functions that are present in the linked
438/// binary (and thus have entries in the debug map). All the debug
439/// information that will be linked (the DIEs, but also the line
440/// tables, ranges, ...) is derived from that set of root DIEs.
441///
442/// The root DIEs are identified because they contain relocations that
443/// correspond to a debug map entry at specific places (the low_pc for
444/// a function, the location for a variable). These relocations are
445/// called ValidRelocs in the DwarfLinker and are gathered as a very
446/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +0000447class DwarfLinker {
448public:
Frederic Rissb9818322015-02-28 00:29:07 +0000449 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
450 : OutputFilename(OutputFilename), Options(Options),
451 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +0000452
Frederic Rissb8b43d52015-03-04 22:07:44 +0000453 ~DwarfLinker() {
454 for (auto *Abbrev : Abbreviations)
455 delete Abbrev;
456 }
457
Frederic Rissd3455182015-01-28 18:27:01 +0000458 /// \brief Link the contents of the DebugMap.
459 bool link(const DebugMap &);
460
461private:
Frederic Riss563cba62015-01-28 22:15:14 +0000462 /// \brief Called at the start of a debug object link.
463 void startDebugObject(DWARFContext &);
464
465 /// \brief Called at the end of a debug object link.
466 void endDebugObject();
467
Frederic Riss1036e642015-02-13 23:18:22 +0000468 /// \defgroup FindValidRelocations Translate debug map into a list
469 /// of relevant relocations
470 ///
471 /// @{
472 struct ValidReloc {
473 uint32_t Offset;
474 uint32_t Size;
475 uint64_t Addend;
476 const DebugMapObject::DebugMapEntry *Mapping;
477
478 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
479 const DebugMapObject::DebugMapEntry *Mapping)
480 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
481
482 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
483 };
484
485 /// \brief The valid relocations for the current DebugMapObject.
486 /// This vector is sorted by relocation offset.
487 std::vector<ValidReloc> ValidRelocs;
488
489 /// \brief Index into ValidRelocs of the next relocation to
490 /// consider. As we walk the DIEs in acsending file offset and as
491 /// ValidRelocs is sorted by file offset, keeping this index
492 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +0000493 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +0000494 unsigned NextValidReloc;
495
496 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
497 const DebugMapObject &DMO);
498
499 bool findValidRelocs(const object::SectionRef &Section,
500 const object::ObjectFile &Obj,
501 const DebugMapObject &DMO);
502
503 void findValidRelocsMachO(const object::SectionRef &Section,
504 const object::MachOObjectFile &Obj,
505 const DebugMapObject &DMO);
506 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +0000507
Frederic Riss84c09a52015-02-13 23:18:34 +0000508 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
509 ///
510 /// @{
511 /// \brief Recursively walk the \p DIE tree and look for DIEs to
512 /// keep. Store that information in \p CU's DIEInfo.
513 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
514 const DebugMapObject &DMO, CompileUnit &CU,
515 unsigned Flags);
516
517 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
518 enum TravesalFlags {
519 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
520 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
521 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
522 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
523 };
524
525 /// \brief Mark the passed DIE as well as all the ones it depends on
526 /// as kept.
527 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
528 CompileUnit::DIEInfo &MyInfo,
529 const DebugMapObject &DMO, CompileUnit &CU,
530 unsigned Flags);
531
532 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
533 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
534 unsigned Flags);
535
536 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
537 CompileUnit &Unit,
538 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
539
540 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
541 CompileUnit &Unit,
542 CompileUnit::DIEInfo &MyInfo,
543 unsigned Flags);
544
545 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
546 CompileUnit::DIEInfo &Info);
547 /// @}
548
Frederic Rissb8b43d52015-03-04 22:07:44 +0000549 /// \defgroup Linking Methods used to link the debug information
550 ///
551 /// @{
552 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
553 /// where useless (as decided by lookForDIEsToKeep()) bits have been
554 /// stripped out and addresses have been rewritten according to the
555 /// debug map.
556 ///
557 /// \param OutOffset is the offset the cloned DIE in the output
558 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +0000559 /// \param PCOffset (while cloning a function scope) is the offset
560 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000561 ///
562 /// \returns the root of the cloned tree.
563 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +0000564 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000565
566 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
567
Frederic Riss31da3242015-03-11 18:45:52 +0000568 /// \brief Information gathered and exchanged between the various
569 /// clone*Attributes helpers about the attributes of a particular DIE.
570 struct AttributesInfo {
571 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
572 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
573
574 AttributesInfo() : OrigHighPc(0), PCOffset(0) {}
575 };
576
Frederic Rissb8b43d52015-03-04 22:07:44 +0000577 /// \brief Helper for cloneDIE.
578 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
579 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +0000580 const AttributeSpec AttrSpec, unsigned AttrSize,
581 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000582
583 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +0000584 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
585 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000586
587 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +0000588 unsigned
589 cloneDieReferenceAttribute(DIE &Die,
590 const DWARFDebugInfoEntryMinimal &InputDIE,
591 AttributeSpec AttrSpec, unsigned AttrSize,
592 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000593
594 /// \brief Helper for cloneDIE.
595 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
596 const DWARFFormValue &Val, unsigned AttrSize);
597
598 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +0000599 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
600 const DWARFFormValue &Val,
601 const CompileUnit &Unit, AttributesInfo &Info);
602
603 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000604 unsigned cloneScalarAttribute(DIE &Die,
605 const DWARFDebugInfoEntryMinimal &InputDIE,
606 const DWARFUnit &U, AttributeSpec AttrSpec,
607 const DWARFFormValue &Val, unsigned AttrSize);
608
Frederic Riss23e20e92015-03-07 01:25:09 +0000609 /// \brief Helper for cloneDIE.
610 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
611 bool isLittleEndian);
612
Frederic Rissb8b43d52015-03-04 22:07:44 +0000613 /// \brief Assign an abbreviation number to \p Abbrev
614 void AssignAbbrev(DIEAbbrev &Abbrev);
615
616 /// \brief FoldingSet that uniques the abbreviations.
617 FoldingSet<DIEAbbrev> AbbreviationsSet;
618 /// \brief Storage for the unique Abbreviations.
619 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
620 /// be changed to a vecot of unique_ptrs.
621 std::vector<DIEAbbrev *> Abbreviations;
622
623 /// \brief DIELoc objects that need to be destructed (but not freed!).
624 std::vector<DIELoc *> DIELocs;
625 /// \brief DIEBlock objects that need to be destructed (but not freed!).
626 std::vector<DIEBlock *> DIEBlocks;
627 /// \brief Allocator used for all the DIEValue objects.
628 BumpPtrAllocator DIEAlloc;
629 /// @}
630
Frederic Riss1b9da422015-02-13 23:18:29 +0000631 /// \defgroup Helpers Various helper methods.
632 ///
633 /// @{
634 const DWARFDebugInfoEntryMinimal *
635 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
636 const DWARFDebugInfoEntryMinimal &DIE,
637 CompileUnit *&ReferencedCU);
638
639 CompileUnit *getUnitForOffset(unsigned Offset);
640
641 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
642 const DWARFDebugInfoEntryMinimal *DIE = nullptr);
Frederic Rissc99ea202015-02-28 00:29:11 +0000643
644 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +0000645 /// @}
646
Frederic Riss563cba62015-01-28 22:15:14 +0000647private:
Frederic Rissd3455182015-01-28 18:27:01 +0000648 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +0000649 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +0000650 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +0000651 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +0000652
653 /// The units of the current debug map object.
654 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +0000655
656 /// The debug map object curently under consideration.
657 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +0000658
659 /// \brief The Dwarf string pool
660 NonRelocatableStringpool StringPool;
Frederic Rissd3455182015-01-28 18:27:01 +0000661};
662
Frederic Riss1b9da422015-02-13 23:18:29 +0000663/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
664/// returning our CompileUnit object instead.
665CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
666 auto CU =
667 std::upper_bound(Units.begin(), Units.end(), Offset,
668 [](uint32_t LHS, const CompileUnit &RHS) {
669 return LHS < RHS.getOrigUnit().getNextUnitOffset();
670 });
671 return CU != Units.end() ? &*CU : nullptr;
672}
673
674/// \brief Resolve the DIE attribute reference that has been
675/// extracted in \p RefValue. The resulting DIE migh be in another
676/// CompileUnit which is stored into \p ReferencedCU.
677/// \returns null if resolving fails for any reason.
678const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
679 DWARFFormValue &RefValue, const DWARFUnit &Unit,
680 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
681 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
682 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
683
684 if ((RefCU = getUnitForOffset(RefOffset)))
685 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
686 return RefDie;
687
688 reportWarning("could not find referenced DIE", &Unit, &DIE);
689 return nullptr;
690}
691
692/// \brief Report a warning to the user, optionaly including
693/// information about a specific \p DIE related to the warning.
694void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
695 const DWARFDebugInfoEntryMinimal *DIE) {
Frederic Rissdef4fb72015-02-28 00:29:01 +0000696 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +0000697 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +0000698 Context = CurrentDebugObject->getObjectFilename();
699 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +0000700
Frederic Rissb9818322015-02-28 00:29:07 +0000701 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +0000702 return;
703
704 errs() << " in DIE:\n";
705 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
706 6 /* Indent */);
707}
708
Frederic Rissc99ea202015-02-28 00:29:11 +0000709bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
710 if (Options.NoOutput)
711 return true;
712
Frederic Rissb52cf522015-02-28 00:42:37 +0000713 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +0000714 return Streamer->init(TheTriple, OutputFilename);
715}
716
Frederic Riss563cba62015-01-28 22:15:14 +0000717/// \brief Recursive helper to gather the child->parent relationships in the
718/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +0000719static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
720 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +0000721 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
722 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
723
724 if (DIE->hasChildren())
725 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
726 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +0000727 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +0000728}
729
Frederic Riss84c09a52015-02-13 23:18:34 +0000730static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
731 switch (Tag) {
732 default:
733 return false;
734 case dwarf::DW_TAG_subprogram:
735 case dwarf::DW_TAG_lexical_block:
736 case dwarf::DW_TAG_subroutine_type:
737 case dwarf::DW_TAG_structure_type:
738 case dwarf::DW_TAG_class_type:
739 case dwarf::DW_TAG_union_type:
740 return true;
741 }
742 llvm_unreachable("Invalid Tag");
743}
744
Frederic Riss563cba62015-01-28 22:15:14 +0000745void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
746 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +0000747 NextValidReloc = 0;
Frederic Riss563cba62015-01-28 22:15:14 +0000748}
749
Frederic Riss1036e642015-02-13 23:18:22 +0000750void DwarfLinker::endDebugObject() {
751 Units.clear();
752 ValidRelocs.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000753
754 for (auto *Block : DIEBlocks)
755 Block->~DIEBlock();
756 for (auto *Loc : DIELocs)
757 Loc->~DIELoc();
758
759 DIEBlocks.clear();
760 DIELocs.clear();
761 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +0000762}
763
764/// \brief Iterate over the relocations of the given \p Section and
765/// store the ones that correspond to debug map entries into the
766/// ValidRelocs array.
767void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
768 const object::MachOObjectFile &Obj,
769 const DebugMapObject &DMO) {
770 StringRef Contents;
771 Section.getContents(Contents);
772 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
773
774 for (const object::RelocationRef &Reloc : Section.relocations()) {
775 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
776 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
777 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
778 uint64_t Offset64;
779 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +0000780 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +0000781 continue;
782 }
783 uint32_t Offset = Offset64;
784 // Mach-o uses REL relocations, the addend is at the relocation offset.
785 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
786
787 auto Sym = Reloc.getSymbol();
788 if (Sym != Obj.symbol_end()) {
789 StringRef SymbolName;
790 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +0000791 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +0000792 continue;
793 }
794 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
795 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
796 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
797 // Do not store the addend. The addend was the address of the
798 // symbol in the object file, the address in the binary that is
799 // stored in the debug map doesn't need to be offseted.
800 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
801 }
802 }
803}
804
805/// \brief Dispatch the valid relocation finding logic to the
806/// appropriate handler depending on the object file format.
807bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
808 const object::ObjectFile &Obj,
809 const DebugMapObject &DMO) {
810 // Dispatch to the right handler depending on the file type.
811 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
812 findValidRelocsMachO(Section, *MachOObj, DMO);
813 else
Frederic Riss1b9da422015-02-13 23:18:29 +0000814 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +0000815
816 if (ValidRelocs.empty())
817 return false;
818
819 // Sort the relocations by offset. We will walk the DIEs linearly in
820 // the file, this allows us to just keep an index in the relocation
821 // array that we advance during our walk, rather than resorting to
822 // some associative container. See DwarfLinker::NextValidReloc.
823 std::sort(ValidRelocs.begin(), ValidRelocs.end());
824 return true;
825}
826
827/// \brief Look for relocations in the debug_info section that match
828/// entries in the debug map. These relocations will drive the Dwarf
829/// link by indicating which DIEs refer to symbols present in the
830/// linked binary.
831/// \returns wether there are any valid relocations in the debug info.
832bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
833 const DebugMapObject &DMO) {
834 // Find the debug_info section.
835 for (const object::SectionRef &Section : Obj.sections()) {
836 StringRef SectionName;
837 Section.getName(SectionName);
838 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
839 if (SectionName != "debug_info")
840 continue;
841 return findValidRelocs(Section, Obj, DMO);
842 }
843 return false;
844}
Frederic Riss563cba62015-01-28 22:15:14 +0000845
Frederic Riss84c09a52015-02-13 23:18:34 +0000846/// \brief Checks that there is a relocation against an actual debug
847/// map entry between \p StartOffset and \p NextOffset.
848///
849/// This function must be called with offsets in strictly ascending
850/// order because it never looks back at relocations it already 'went past'.
851/// \returns true and sets Info.InDebugMap if it is the case.
852bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
853 CompileUnit::DIEInfo &Info) {
854 assert(NextValidReloc == 0 ||
855 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
856 if (NextValidReloc >= ValidRelocs.size())
857 return false;
858
859 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
860
861 // We might need to skip some relocs that we didn't consider. For
862 // example the high_pc of a discarded DIE might contain a reloc that
863 // is in the list because it actually corresponds to the start of a
864 // function that is in the debug map.
865 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
866 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
867
868 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
869 return false;
870
871 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +0000872 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +0000873 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
874 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
875 ValidReloc.Mapping->getValue().ObjectAddress,
876 ValidReloc.Mapping->getValue().BinaryAddress);
877
Frederic Riss31da3242015-03-11 18:45:52 +0000878 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
879 ValidReloc.Addend -
880 ValidReloc.Mapping->getValue().ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +0000881 Info.InDebugMap = true;
882 return true;
883}
884
885/// \brief Get the starting and ending (exclusive) offset for the
886/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
887/// supposed to point to the position of the first attribute described
888/// by \p Abbrev.
889/// \return [StartOffset, EndOffset) as a pair.
890static std::pair<uint32_t, uint32_t>
891getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
892 unsigned Offset, const DWARFUnit &Unit) {
893 DataExtractor Data = Unit.getDebugInfoExtractor();
894
895 for (unsigned i = 0; i < Idx; ++i)
896 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
897
898 uint32_t End = Offset;
899 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
900
901 return std::make_pair(Offset, End);
902}
903
904/// \brief Check if a variable describing DIE should be kept.
905/// \returns updated TraversalFlags.
906unsigned DwarfLinker::shouldKeepVariableDIE(
907 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
908 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
909 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
910
911 // Global variables with constant value can always be kept.
912 if (!(Flags & TF_InFunctionScope) &&
913 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
914 MyInfo.InDebugMap = true;
915 return Flags | TF_Keep;
916 }
917
918 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
919 if (LocationIdx == -1U)
920 return Flags;
921
922 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
923 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
924 uint32_t LocationOffset, LocationEndOffset;
925 std::tie(LocationOffset, LocationEndOffset) =
926 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
927
928 // See if there is a relocation to a valid debug map entry inside
929 // this variable's location. The order is important here. We want to
930 // always check in the variable has a valid relocation, so that the
931 // DIEInfo is filled. However, we don't want a static variable in a
932 // function to force us to keep the enclosing function.
933 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
934 (Flags & TF_InFunctionScope))
935 return Flags;
936
Frederic Rissb9818322015-02-28 00:29:07 +0000937 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +0000938 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
939
940 return Flags | TF_Keep;
941}
942
943/// \brief Check if a function describing DIE should be kept.
944/// \returns updated TraversalFlags.
945unsigned DwarfLinker::shouldKeepSubprogramDIE(
946 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
947 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
948 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
949
950 Flags |= TF_InFunctionScope;
951
952 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
953 if (LowPcIdx == -1U)
954 return Flags;
955
956 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
957 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
958 uint32_t LowPcOffset, LowPcEndOffset;
959 std::tie(LowPcOffset, LowPcEndOffset) =
960 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
961
962 uint64_t LowPc =
963 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
964 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
965 if (LowPc == -1ULL ||
966 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
967 return Flags;
968
Frederic Rissb9818322015-02-28 00:29:07 +0000969 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +0000970 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
971
Frederic Riss1af75f72015-03-12 18:45:10 +0000972 Flags |= TF_Keep;
973
974 DWARFFormValue HighPcValue;
975 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
976 reportWarning("Function without high_pc. Range will be discarded.\n",
977 &OrigUnit, &DIE);
978 return Flags;
979 }
980
981 uint64_t HighPc;
982 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
983 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
984 } else {
985 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
986 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
987 }
988
989 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
990 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +0000991}
992
993/// \brief Check if a DIE should be kept.
994/// \returns updated TraversalFlags.
995unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
996 CompileUnit &Unit,
997 CompileUnit::DIEInfo &MyInfo,
998 unsigned Flags) {
999 switch (DIE.getTag()) {
1000 case dwarf::DW_TAG_constant:
1001 case dwarf::DW_TAG_variable:
1002 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1003 case dwarf::DW_TAG_subprogram:
1004 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1005 case dwarf::DW_TAG_module:
1006 case dwarf::DW_TAG_imported_module:
1007 case dwarf::DW_TAG_imported_declaration:
1008 case dwarf::DW_TAG_imported_unit:
1009 // We always want to keep these.
1010 return Flags | TF_Keep;
1011 }
1012
1013 return Flags;
1014}
1015
Frederic Riss84c09a52015-02-13 23:18:34 +00001016/// \brief Mark the passed DIE as well as all the ones it depends on
1017/// as kept.
1018///
1019/// This function is called by lookForDIEsToKeep on DIEs that are
1020/// newly discovered to be needed in the link. It recursively calls
1021/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1022/// TraversalFlags to inform it that it's not doing the primary DIE
1023/// tree walk.
1024void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1025 CompileUnit::DIEInfo &MyInfo,
1026 const DebugMapObject &DMO,
1027 CompileUnit &CU, unsigned Flags) {
1028 const DWARFUnit &Unit = CU.getOrigUnit();
1029 MyInfo.Keep = true;
1030
1031 // First mark all the parent chain as kept.
1032 unsigned AncestorIdx = MyInfo.ParentIdx;
1033 while (!CU.getInfo(AncestorIdx).Keep) {
1034 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1035 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1036 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1037 }
1038
1039 // Then we need to mark all the DIEs referenced by this DIE's
1040 // attributes as kept.
1041 DataExtractor Data = Unit.getDebugInfoExtractor();
1042 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1043 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1044
1045 // Mark all DIEs referenced through atttributes as kept.
1046 for (const auto &AttrSpec : Abbrev->attributes()) {
1047 DWARFFormValue Val(AttrSpec.Form);
1048
1049 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1050 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1051 continue;
1052 }
1053
1054 Val.extractValue(Data, &Offset, &Unit);
1055 CompileUnit *ReferencedCU;
1056 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1057 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1058 TF_Keep | TF_DependencyWalk);
1059 }
1060}
1061
1062/// \brief Recursively walk the \p DIE tree and look for DIEs to
1063/// keep. Store that information in \p CU's DIEInfo.
1064///
1065/// This function is the entry point of the DIE selection
1066/// algorithm. It is expected to walk the DIE tree in file order and
1067/// (though the mediation of its helper) call hasValidRelocation() on
1068/// each DIE that might be a 'root DIE' (See DwarfLinker class
1069/// comment).
1070/// While walking the dependencies of root DIEs, this function is
1071/// also called, but during these dependency walks the file order is
1072/// not respected. The TF_DependencyWalk flag tells us which kind of
1073/// traversal we are currently doing.
1074void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1075 const DebugMapObject &DMO, CompileUnit &CU,
1076 unsigned Flags) {
1077 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1078 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1079 bool AlreadyKept = MyInfo.Keep;
1080
1081 // If the Keep flag is set, we are marking a required DIE's
1082 // dependencies. If our target is already marked as kept, we're all
1083 // set.
1084 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1085 return;
1086
1087 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1088 // because it would screw up the relocation finding logic.
1089 if (!(Flags & TF_DependencyWalk))
1090 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1091
1092 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1093 if (!AlreadyKept && (Flags & TF_Keep))
1094 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1095
1096 // The TF_ParentWalk flag tells us that we are currently walking up
1097 // the parent chain of a required DIE, and we don't want to mark all
1098 // the children of the parents as kept (consider for example a
1099 // DW_TAG_namespace node in the parent chain). There are however a
1100 // set of DIE types for which we want to ignore that directive and still
1101 // walk their children.
1102 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1103 Flags &= ~TF_ParentWalk;
1104
1105 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1106 return;
1107
1108 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1109 Child = Child->getSibling())
1110 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1111}
1112
Frederic Rissb8b43d52015-03-04 22:07:44 +00001113/// \brief Assign an abbreviation numer to \p Abbrev.
1114///
1115/// Our DIEs get freed after every DebugMapObject has been processed,
1116/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1117/// the instances hold by the DIEs. When we encounter an abbreviation
1118/// that we don't know, we create a permanent copy of it.
1119void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1120 // Check the set for priors.
1121 FoldingSetNodeID ID;
1122 Abbrev.Profile(ID);
1123 void *InsertToken;
1124 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1125
1126 // If it's newly added.
1127 if (InSet) {
1128 // Assign existing abbreviation number.
1129 Abbrev.setNumber(InSet->getNumber());
1130 } else {
1131 // Add to abbreviation list.
1132 Abbreviations.push_back(
1133 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1134 for (const auto &Attr : Abbrev.getData())
1135 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1136 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1137 // Assign the unique abbreviation number.
1138 Abbrev.setNumber(Abbreviations.size());
1139 Abbreviations.back()->setNumber(Abbreviations.size());
1140 }
1141}
1142
1143/// \brief Clone a string attribute described by \p AttrSpec and add
1144/// it to \p Die.
1145/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001146unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1147 const DWARFFormValue &Val,
1148 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001149 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001150 const char *String = *Val.getAsCString(&U);
1151 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001152 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Frederic Rissef648462015-03-06 17:56:30 +00001153 new (DIEAlloc) DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001154 return 4;
1155}
1156
1157/// \brief Clone an attribute referencing another DIE and add
1158/// it to \p Die.
1159/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001160unsigned DwarfLinker::cloneDieReferenceAttribute(
1161 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1162 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1163 const DWARFUnit &U) {
1164 uint32_t Ref = *Val.getAsReference(&U);
1165 DIE *NewRefDie = nullptr;
1166 CompileUnit *RefUnit = nullptr;
1167 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1168
1169 if (!(RefUnit = getUnitForOffset(Ref)) ||
1170 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1171 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1172 if (!AttributeString)
1173 AttributeString = "DW_AT_???";
1174 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1175 ". Dropping.",
1176 &U, &InputDIE);
1177 return 0;
1178 }
1179
1180 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1181 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1182 if (!RefInfo.Clone) {
1183 assert(Ref > InputDIE.getOffset());
1184 // We haven't cloned this DIE yet. Just create an empty one and
1185 // store it. It'll get really cloned when we process it.
1186 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1187 }
1188 NewRefDie = RefInfo.Clone;
1189
1190 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1191 // We cannot currently rely on a DIEEntry to emit ref_addr
1192 // references, because the implementation calls back to DwarfDebug
1193 // to find the unit offset. (We don't have a DwarfDebug)
1194 // FIXME: we should be able to design DIEEntry reliance on
1195 // DwarfDebug away.
1196 DIEInteger *Attr;
1197 if (Ref < InputDIE.getOffset()) {
1198 // We must have already cloned that DIE.
1199 uint32_t NewRefOffset =
1200 RefUnit->getStartOffset() + NewRefDie->getOffset();
1201 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1202 } else {
1203 // A forward reference. Note and fixup later.
1204 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
1205 RefUnit->noteForwardReference(NewRefDie, Attr);
1206 }
1207 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1208 Attr);
1209 return AttrSize;
1210 }
1211
Frederic Rissb8b43d52015-03-04 22:07:44 +00001212 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss9833de62015-03-06 23:22:53 +00001213 new (DIEAlloc) DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001214 return AttrSize;
1215}
1216
1217/// \brief Clone an attribute of block form (locations, constants) and add
1218/// it to \p Die.
1219/// \returns the size of the new attribute.
1220unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1221 const DWARFFormValue &Val,
1222 unsigned AttrSize) {
1223 DIE *Attr;
1224 DIEValue *Value;
1225 DIELoc *Loc = nullptr;
1226 DIEBlock *Block = nullptr;
1227 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001228 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001229 Loc = new (DIEAlloc) DIELoc();
1230 DIELocs.push_back(Loc);
1231 } else {
1232 Block = new (DIEAlloc) DIEBlock();
1233 DIEBlocks.push_back(Block);
1234 }
1235 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1236 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1237 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1238 for (auto Byte : Bytes)
1239 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1240 new (DIEAlloc) DIEInteger(Byte));
1241 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1242 // the DIE class, this if could be replaced by
1243 // Attr->setSize(Bytes.size()).
1244 if (Streamer) {
1245 if (Loc)
1246 Loc->ComputeSize(&Streamer->getAsmPrinter());
1247 else
1248 Block->ComputeSize(&Streamer->getAsmPrinter());
1249 }
1250 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1251 Value);
1252 return AttrSize;
1253}
1254
Frederic Riss31da3242015-03-11 18:45:52 +00001255/// \brief Clone an address attribute and add it to \p Die.
1256/// \returns the size of the new attribute.
1257unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1258 const DWARFFormValue &Val,
1259 const CompileUnit &Unit,
1260 AttributesInfo &Info) {
1261 int64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1262 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1263 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1264 Die.getTag() == dwarf::DW_TAG_lexical_block)
1265 Addr += Info.PCOffset;
1266 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1267 // If we have a high_pc recorded for the input DIE, use
1268 // it. Otherwise (when no relocations where applied) just use the
1269 // one we just decoded.
1270 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1271 }
1272
1273 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1274 static_cast<dwarf::Form>(AttrSpec.Form),
1275 new (DIEAlloc) DIEInteger(Addr));
1276 return Unit.getOrigUnit().getAddressByteSize();
1277}
1278
Frederic Rissb8b43d52015-03-04 22:07:44 +00001279/// \brief Clone a scalar attribute and add it to \p Die.
1280/// \returns the size of the new attribute.
1281unsigned DwarfLinker::cloneScalarAttribute(
1282 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, const DWARFUnit &U,
1283 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) {
1284 uint64_t Value;
1285 if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1286 Value = *Val.getAsSectionOffset();
1287 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1288 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001289 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1290 Value = *OptionalValue;
1291 else {
1292 reportWarning("Unsupported scalar attribute form. Dropping attribute.", &U,
1293 &InputDIE);
1294 return 0;
1295 }
1296 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1297 new (DIEAlloc) DIEInteger(Value));
1298 return AttrSize;
1299}
1300
1301/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1302/// value \p Val, and add it to \p Die.
1303/// \returns the size of the cloned attribute.
1304unsigned DwarfLinker::cloneAttribute(DIE &Die,
1305 const DWARFDebugInfoEntryMinimal &InputDIE,
1306 CompileUnit &Unit,
1307 const DWARFFormValue &Val,
1308 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00001309 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001310 const DWARFUnit &U = Unit.getOrigUnit();
1311
1312 switch (AttrSpec.Form) {
1313 case dwarf::DW_FORM_strp:
1314 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00001315 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001316 case dwarf::DW_FORM_ref_addr:
1317 case dwarf::DW_FORM_ref1:
1318 case dwarf::DW_FORM_ref2:
1319 case dwarf::DW_FORM_ref4:
1320 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00001321 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1322 U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001323 case dwarf::DW_FORM_block:
1324 case dwarf::DW_FORM_block1:
1325 case dwarf::DW_FORM_block2:
1326 case dwarf::DW_FORM_block4:
1327 case dwarf::DW_FORM_exprloc:
1328 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1329 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00001330 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001331 case dwarf::DW_FORM_data1:
1332 case dwarf::DW_FORM_data2:
1333 case dwarf::DW_FORM_data4:
1334 case dwarf::DW_FORM_data8:
1335 case dwarf::DW_FORM_udata:
1336 case dwarf::DW_FORM_sdata:
1337 case dwarf::DW_FORM_sec_offset:
1338 case dwarf::DW_FORM_flag:
1339 case dwarf::DW_FORM_flag_present:
1340 return cloneScalarAttribute(Die, InputDIE, U, AttrSpec, Val, AttrSize);
1341 default:
1342 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1343 &InputDIE);
1344 }
1345
1346 return 0;
1347}
1348
Frederic Riss23e20e92015-03-07 01:25:09 +00001349/// \brief Apply the valid relocations found by findValidRelocs() to
1350/// the buffer \p Data, taking into account that Data is at \p BaseOffset
1351/// in the debug_info section.
1352///
1353/// Like for findValidRelocs(), this function must be called with
1354/// monotonic \p BaseOffset values.
1355///
1356/// \returns wether any reloc has been applied.
1357bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1358 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00001359 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00001360 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1361 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00001362 if (NextValidReloc >= ValidRelocs.size())
1363 return false;
1364
1365 // Skip relocs that haven't been applied.
1366 while (NextValidReloc < ValidRelocs.size() &&
1367 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1368 ++NextValidReloc;
1369
1370 bool Applied = false;
1371 uint64_t EndOffset = BaseOffset + Data.size();
1372 while (NextValidReloc < ValidRelocs.size() &&
1373 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1374 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1375 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1376 assert(ValidReloc.Offset - BaseOffset < Data.size());
1377 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1378 char Buf[8];
1379 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1380 Value += ValidReloc.Addend;
1381 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1382 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1383 Buf[i] = uint8_t(Value >> (Index * 8));
1384 }
1385 assert(ValidReloc.Size <= sizeof(Buf));
1386 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1387 Applied = true;
1388 }
1389
1390 return Applied;
1391}
1392
Frederic Rissb8b43d52015-03-04 22:07:44 +00001393/// \brief Recursively clone \p InputDIE's subtrees that have been
1394/// selected to appear in the linked output.
1395///
1396/// \param OutOffset is the Offset where the newly created DIE will
1397/// lie in the linked compile unit.
1398///
1399/// \returns the cloned DIE object or null if nothing was selected.
1400DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00001401 CompileUnit &Unit, int64_t PCOffset,
1402 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001403 DWARFUnit &U = Unit.getOrigUnit();
1404 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001405 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001406
1407 // Should the DIE appear in the output?
1408 if (!Unit.getInfo(Idx).Keep)
1409 return nullptr;
1410
1411 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00001412 // The DIE might have been already created by a forward reference
1413 // (see cloneDieReferenceAttribute()).
1414 DIE *Die = Info.Clone;
1415 if (!Die)
1416 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1417 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00001418 Die->setOffset(OutOffset);
1419
1420 // Extract and clone every attribute.
1421 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00001422 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00001423 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00001424
1425 // We could copy the data only if we need to aply a relocation to
1426 // it. After testing, it seems there is no performance downside to
1427 // doing the copy unconditionally, and it makes the code simpler.
1428 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1429 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1430 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00001431 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1432 // If we applied relocations, we store the value of high_pc that was
1433 // potentially stored in the input DIE. If high_pc is an address
1434 // (Dwarf version == 2), then it might have been relocated to a
1435 // totally unrelated value (because the end address in the object
1436 // file might be start address of another function which got moved
1437 // independantly by the linker). The computation of the actual
1438 // high_pc value is done in cloneAddressAttribute().
1439 AttrInfo.OrigHighPc =
1440 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
1441 }
Frederic Riss23e20e92015-03-07 01:25:09 +00001442
1443 // Reset the Offset to 0 as we will be working on the local copy of
1444 // the data.
1445 Offset = 0;
1446
Frederic Rissb8b43d52015-03-04 22:07:44 +00001447 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1448 Offset += getULEB128Size(Abbrev->getCode());
1449
Frederic Riss31da3242015-03-11 18:45:52 +00001450 // We are entering a subprogram. Get and propagate the PCOffset.
1451 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1452 PCOffset = Info.AddrAdjust;
1453 AttrInfo.PCOffset = PCOffset;
1454
Frederic Rissb8b43d52015-03-04 22:07:44 +00001455 for (const auto &AttrSpec : Abbrev->attributes()) {
1456 DWARFFormValue Val(AttrSpec.Form);
1457 uint32_t AttrSize = Offset;
1458 Val.extractValue(Data, &Offset, &U);
1459 AttrSize = Offset - AttrSize;
1460
Frederic Riss31da3242015-03-11 18:45:52 +00001461 OutOffset +=
1462 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001463 }
1464
1465 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1466 // If a scope DIE is kept, we must have kept at least one child. If
1467 // it's not the case, we'll just be emitting one wasteful end of
1468 // children marker, but things won't break.
1469 if (InputDIE.hasChildren())
1470 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1471 // Assign a permanent abbrev number
1472 AssignAbbrev(Die->getAbbrev());
1473
1474 // Add the size of the abbreviation number to the output offset.
1475 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1476
1477 if (!Abbrev->hasChildren()) {
1478 // Update our size.
1479 Die->setSize(OutOffset - Die->getOffset());
1480 return Die;
1481 }
1482
1483 // Recursively clone children.
1484 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1485 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00001486 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001487 Die->addChild(std::unique_ptr<DIE>(Clone));
1488 OutOffset = Clone->getOffset() + Clone->getSize();
1489 }
1490 }
1491
1492 // Account for the end of children marker.
1493 OutOffset += sizeof(int8_t);
1494 // Update our size.
1495 Die->setSize(OutOffset - Die->getOffset());
1496 return Die;
1497}
1498
Frederic Rissd3455182015-01-28 18:27:01 +00001499bool DwarfLinker::link(const DebugMap &Map) {
1500
1501 if (Map.begin() == Map.end()) {
1502 errs() << "Empty debug map.\n";
1503 return false;
1504 }
1505
Frederic Rissc99ea202015-02-28 00:29:11 +00001506 if (!createStreamer(Map.getTriple(), OutputFilename))
1507 return false;
1508
Frederic Rissb8b43d52015-03-04 22:07:44 +00001509 // Size of the DIEs (and headers) generated for the linked output.
1510 uint64_t OutputDebugInfoSize = 0;
1511
Frederic Rissd3455182015-01-28 18:27:01 +00001512 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001513 CurrentDebugObject = Obj.get();
1514
Frederic Rissb9818322015-02-28 00:29:07 +00001515 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00001516 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1517 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1518 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001519 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00001520 continue;
1521 }
1522
Frederic Riss1036e642015-02-13 23:18:22 +00001523 // Look for relocations that correspond to debug map entries.
1524 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00001525 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00001526 outs() << "No valid relocations found. Skipping.\n";
1527 continue;
1528 }
1529
Frederic Riss563cba62015-01-28 22:15:14 +00001530 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00001531 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss563cba62015-01-28 22:15:14 +00001532 startDebugObject(DwarfContext);
Frederic Rissd3455182015-01-28 18:27:01 +00001533
Frederic Riss563cba62015-01-28 22:15:14 +00001534 // In a first phase, just read in the debug info and store the DIE
1535 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00001536 for (const auto &CU : DwarfContext.compile_units()) {
1537 auto *CUDie = CU->getCompileUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00001538 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00001539 outs() << "Input compilation unit:";
1540 CUDie->dump(outs(), CU.get(), 0);
1541 }
Frederic Riss563cba62015-01-28 22:15:14 +00001542 Units.emplace_back(*CU);
Frederic Riss9aa725b2015-02-13 23:18:31 +00001543 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00001544 }
Frederic Riss563cba62015-01-28 22:15:14 +00001545
Frederic Riss84c09a52015-02-13 23:18:34 +00001546 // Then mark all the DIEs that need to be present in the linked
1547 // output and collect some information about them. Note that this
1548 // loop can not be merged with the previous one becaue cross-cu
1549 // references require the ParentIdx to be setup for every CU in
1550 // the object file before calling this.
1551 for (auto &CurrentUnit : Units)
1552 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1553 CurrentUnit, 0);
1554
Frederic Riss23e20e92015-03-07 01:25:09 +00001555 // The calls to applyValidRelocs inside cloneDIE will walk the
1556 // reloc array again (in the same way findValidRelocsInDebugInfo()
1557 // did). We need to reset the NextValidReloc index to the beginning.
1558 NextValidReloc = 0;
1559
Frederic Rissb8b43d52015-03-04 22:07:44 +00001560 // Construct the output DIE tree by cloning the DIEs we chose to
1561 // keep above. If there are no valid relocs, then there's nothing
1562 // to clone/emit.
1563 if (!ValidRelocs.empty())
1564 for (auto &CurrentUnit : Units) {
1565 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00001566 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00001567 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
1568 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001569 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00001570 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001571 }
1572
1573 // Emit all the compile unit's debug information.
1574 if (!ValidRelocs.empty() && !Options.NoOutput)
1575 for (auto &CurrentUnit : Units) {
Frederic Riss9833de62015-03-06 23:22:53 +00001576 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001577 Streamer->emitCompileUnitHeader(CurrentUnit);
1578 if (!CurrentUnit.getOutputUnitDIE())
1579 continue;
1580 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1581 }
1582
Frederic Riss563cba62015-01-28 22:15:14 +00001583 // Clean-up before starting working on the next object.
1584 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00001585 }
1586
Frederic Rissb8b43d52015-03-04 22:07:44 +00001587 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00001588 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001589 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00001590 Streamer->emitStrings(StringPool);
1591 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00001592
Frederic Rissc99ea202015-02-28 00:29:11 +00001593 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00001594}
1595}
Frederic Rissd3455182015-01-28 18:27:01 +00001596
Frederic Rissb9818322015-02-28 00:29:07 +00001597bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1598 const LinkOptions &Options) {
1599 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00001600 return Linker.link(DM);
1601}
1602}
Frederic Riss231f7142014-12-12 17:31:24 +00001603}