blob: 7c2be163c7528af730112eb7c333d13555ff5eec [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 Rissc99ea202015-02-28 00:29:11 +000013#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000014#include "llvm/CodeGen/DIE.h"
Zachary Turner82af9432015-01-30 18:07:45 +000015#include "llvm/DebugInfo/DWARF/DWARFContext.h"
16#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000017#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000018#include "llvm/MC/MCAsmBackend.h"
19#include "llvm/MC/MCAsmInfo.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCCodeEmitter.h"
22#include "llvm/MC/MCInstrInfo.h"
23#include "llvm/MC/MCObjectFileInfo.h"
24#include "llvm/MC/MCRegisterInfo.h"
25#include "llvm/MC/MCStreamer.h"
Frederic Riss1036e642015-02-13 23:18:22 +000026#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000027#include "llvm/Support/Dwarf.h"
28#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000029#include "llvm/Support/TargetRegistry.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000032#include <string>
Frederic Riss231f7142014-12-12 17:31:24 +000033
34namespace llvm {
35namespace dsymutil {
36
Frederic Rissd3455182015-01-28 18:27:01 +000037namespace {
38
Frederic Rissdef4fb72015-02-28 00:29:01 +000039void warn(const Twine &Warning, const Twine &Context) {
40 errs() << Twine("while processing ") + Context + ":\n";
41 errs() << Twine("warning: ") + Warning + "\n";
42}
43
Frederic Rissc99ea202015-02-28 00:29:11 +000044bool error(const Twine &Error, const Twine &Context) {
45 errs() << Twine("while processing ") + Context + ":\n";
46 errs() << Twine("error: ") + Error + "\n";
47 return false;
48}
49
Frederic Riss563cba62015-01-28 22:15:14 +000050/// \brief Stores all information relating to a compile unit, be it in
51/// its original instance in the object file to its brand new cloned
52/// and linked DIE tree.
53class CompileUnit {
54public:
55 /// \brief Information gathered about a DIE in the object file.
56 struct DIEInfo {
Frederic Riss84c09a52015-02-13 23:18:34 +000057 uint64_t Address; ///< Linked address of the described entity.
58 uint32_t ParentIdx; ///< The index of this DIE's parent.
59 bool Keep; ///< Is the DIE part of the linked output?
60 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +000061 };
62
63 CompileUnit(DWARFUnit &OrigUnit) : OrigUnit(OrigUnit) {
64 Info.resize(OrigUnit.getNumDIEs());
65 }
66
Frederic Rissc3349d42015-02-13 23:18:27 +000067 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +000068
Frederic Rissb8b43d52015-03-04 22:07:44 +000069 DIE *getOutputUnitDIE() const { return CUDie.get(); }
70 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
71
Frederic Riss563cba62015-01-28 22:15:14 +000072 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
73 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
74
Frederic Rissb8b43d52015-03-04 22:07:44 +000075 uint64_t getStartOffset() const { return StartOffset; }
76 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
77
78 /// \brief Set the start and end offsets for this unit. Must be
79 /// called after the CU's DIEs have been cloned. The unit start
80 /// offset will be set to \p DebugInfoSize.
81 /// \returns the next unit offset (which is also the current
82 /// debug_info section size).
83 uint64_t computeOffsets(uint64_t DebugInfoSize);
84
Frederic Riss563cba62015-01-28 22:15:14 +000085private:
86 DWARFUnit &OrigUnit;
Frederic Rissb8b43d52015-03-04 22:07:44 +000087 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
88 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
89
90 uint64_t StartOffset;
91 uint64_t NextUnitOffset;
Frederic Riss563cba62015-01-28 22:15:14 +000092};
93
Frederic Rissb8b43d52015-03-04 22:07:44 +000094uint64_t CompileUnit::computeOffsets(uint64_t DebugInfoSize) {
95 StartOffset = DebugInfoSize;
96 NextUnitOffset = StartOffset + 11 /* Header size */;
97 // The root DIE might be null, meaning that the Unit had nothing to
98 // contribute to the linked output. In that case, we will emit the
99 // unit header without any actual DIE.
100 if (CUDie)
101 NextUnitOffset += CUDie->getSize();
102 return NextUnitOffset;
103}
104
Frederic Rissc99ea202015-02-28 00:29:11 +0000105/// \brief The Dwarf streaming logic
106///
107/// All interactions with the MC layer that is used to build the debug
108/// information binary representation are handled in this class.
109class DwarfStreamer {
110 /// \defgroup MCObjects MC layer objects constructed by the streamer
111 /// @{
112 std::unique_ptr<MCRegisterInfo> MRI;
113 std::unique_ptr<MCAsmInfo> MAI;
114 std::unique_ptr<MCObjectFileInfo> MOFI;
115 std::unique_ptr<MCContext> MC;
116 MCAsmBackend *MAB; // Owned by MCStreamer
117 std::unique_ptr<MCInstrInfo> MII;
118 std::unique_ptr<MCSubtargetInfo> MSTI;
119 MCCodeEmitter *MCE; // Owned by MCStreamer
120 MCStreamer *MS; // Owned by AsmPrinter
121 std::unique_ptr<TargetMachine> TM;
122 std::unique_ptr<AsmPrinter> Asm;
123 /// @}
124
125 /// \brief the file we stream the linked Dwarf to.
126 std::unique_ptr<raw_fd_ostream> OutFile;
127
128public:
129 /// \brief Actually create the streamer and the ouptut file.
130 ///
131 /// This could be done directly in the constructor, but it feels
132 /// more natural to handle errors through return value.
133 bool init(Triple TheTriple, StringRef OutputFilename);
134
Frederic Rissb8b43d52015-03-04 22:07:44 +0000135 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000136 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000137
138 AsmPrinter &getAsmPrinter() const { return *Asm; }
139
140 /// \brief Set the current output section to debug_info and change
141 /// the MC Dwarf version to \p DwarfVersion.
142 void switchToDebugInfoSection(unsigned DwarfVersion);
143
144 /// \brief Emit the compilation unit header for \p Unit in the
145 /// debug_info section.
146 ///
147 /// As a side effect, this also switches the current Dwarf version
148 /// of the MC layer to the one of U.getOrigUnit().
149 void emitCompileUnitHeader(CompileUnit &Unit);
150
151 /// \brief Recursively emit the DIE tree rooted at \p Die.
152 void emitDIE(DIE &Die);
153
154 /// \brief Emit the abbreviation table \p Abbrevs to the
155 /// debug_abbrev section.
156 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissc99ea202015-02-28 00:29:11 +0000157};
158
159bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
160 std::string ErrorStr;
161 std::string TripleName;
162 StringRef Context = "dwarf streamer init";
163
164 // Get the target.
165 const Target *TheTarget =
166 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
167 if (!TheTarget)
168 return error(ErrorStr, Context);
169 TripleName = TheTriple.getTriple();
170
171 // Create all the MC Objects.
172 MRI.reset(TheTarget->createMCRegInfo(TripleName));
173 if (!MRI)
174 return error(Twine("no register info for target ") + TripleName, Context);
175
176 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
177 if (!MAI)
178 return error("no asm info for target " + TripleName, Context);
179
180 MOFI.reset(new MCObjectFileInfo);
181 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
182 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
183 *MC);
184
185 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
186 if (!MAB)
187 return error("no asm backend for target " + TripleName, Context);
188
189 MII.reset(TheTarget->createMCInstrInfo());
190 if (!MII)
191 return error("no instr info info for target " + TripleName, Context);
192
193 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
194 if (!MSTI)
195 return error("no subtarget info for target " + TripleName, Context);
196
197 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MSTI, *MC);
198 if (!MCE)
199 return error("no code emitter for target " + TripleName, Context);
200
201 // Create the output file.
202 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000203 OutFile =
204 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000205 if (EC)
206 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
207
208 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
209 *MSTI, false);
210 if (!MS)
211 return error("no object streamer for target " + TripleName, Context);
212
213 // Finally create the AsmPrinter we'll use to emit the DIEs.
214 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
215 if (!TM)
216 return error("no target machine for target " + TripleName, Context);
217
218 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
219 if (!Asm)
220 return error("no asm printer for target " + TripleName, Context);
221
222 return true;
223}
224
225bool DwarfStreamer::finish() {
226 MS->Finish();
227 return true;
228}
229
Frederic Rissb8b43d52015-03-04 22:07:44 +0000230/// \brief Set the current output section to debug_info and change
231/// the MC Dwarf version to \p DwarfVersion.
232void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
233 MS->SwitchSection(MOFI->getDwarfInfoSection());
234 MC->setDwarfVersion(DwarfVersion);
235}
236
237/// \brief Emit the compilation unit header for \p Unit in the
238/// debug_info section.
239///
240/// A Dwarf scetion header is encoded as:
241/// uint32_t Unit length (omiting this field)
242/// uint16_t Version
243/// uint32_t Abbreviation table offset
244/// uint8_t Address size
245///
246/// Leading to a total of 11 bytes.
247void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
248 unsigned Version = Unit.getOrigUnit().getVersion();
249 switchToDebugInfoSection(Version);
250
251 // Emit size of content not including length itself. The size has
252 // already been computed in CompileUnit::computeOffsets(). Substract
253 // 4 to that size to account for the length field.
254 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
255 Asm->EmitInt16(Version);
256 // We share one abbreviations table across all units so it's always at the
257 // start of the section.
258 Asm->EmitInt32(0);
259 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
260}
261
262/// \brief Emit the \p Abbrevs array as the shared abbreviation table
263/// for the linked Dwarf file.
264void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
265 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
266 Asm->emitDwarfAbbrevs(Abbrevs);
267}
268
269/// \brief Recursively emit the DIE tree rooted at \p Die.
270void DwarfStreamer::emitDIE(DIE &Die) {
271 MS->SwitchSection(MOFI->getDwarfInfoSection());
272 Asm->emitDwarfDIE(Die);
273}
274
Frederic Rissd3455182015-01-28 18:27:01 +0000275/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000276///
277/// The link of the dwarf information from the object files will be
278/// driven by the selection of 'root DIEs', which are DIEs that
279/// describe variables or functions that are present in the linked
280/// binary (and thus have entries in the debug map). All the debug
281/// information that will be linked (the DIEs, but also the line
282/// tables, ranges, ...) is derived from that set of root DIEs.
283///
284/// The root DIEs are identified because they contain relocations that
285/// correspond to a debug map entry at specific places (the low_pc for
286/// a function, the location for a variable). These relocations are
287/// called ValidRelocs in the DwarfLinker and are gathered as a very
288/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +0000289class DwarfLinker {
290public:
Frederic Rissb9818322015-02-28 00:29:07 +0000291 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
292 : OutputFilename(OutputFilename), Options(Options),
293 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +0000294
Frederic Rissb8b43d52015-03-04 22:07:44 +0000295 ~DwarfLinker() {
296 for (auto *Abbrev : Abbreviations)
297 delete Abbrev;
298 }
299
Frederic Rissd3455182015-01-28 18:27:01 +0000300 /// \brief Link the contents of the DebugMap.
301 bool link(const DebugMap &);
302
303private:
Frederic Riss563cba62015-01-28 22:15:14 +0000304 /// \brief Called at the start of a debug object link.
305 void startDebugObject(DWARFContext &);
306
307 /// \brief Called at the end of a debug object link.
308 void endDebugObject();
309
Frederic Riss1036e642015-02-13 23:18:22 +0000310 /// \defgroup FindValidRelocations Translate debug map into a list
311 /// of relevant relocations
312 ///
313 /// @{
314 struct ValidReloc {
315 uint32_t Offset;
316 uint32_t Size;
317 uint64_t Addend;
318 const DebugMapObject::DebugMapEntry *Mapping;
319
320 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
321 const DebugMapObject::DebugMapEntry *Mapping)
322 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
323
324 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
325 };
326
327 /// \brief The valid relocations for the current DebugMapObject.
328 /// This vector is sorted by relocation offset.
329 std::vector<ValidReloc> ValidRelocs;
330
331 /// \brief Index into ValidRelocs of the next relocation to
332 /// consider. As we walk the DIEs in acsending file offset and as
333 /// ValidRelocs is sorted by file offset, keeping this index
334 /// uptodate is all we have to do to have a cheap lookup during the
335 /// root DIE selection.
336 unsigned NextValidReloc;
337
338 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
339 const DebugMapObject &DMO);
340
341 bool findValidRelocs(const object::SectionRef &Section,
342 const object::ObjectFile &Obj,
343 const DebugMapObject &DMO);
344
345 void findValidRelocsMachO(const object::SectionRef &Section,
346 const object::MachOObjectFile &Obj,
347 const DebugMapObject &DMO);
348 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +0000349
Frederic Riss84c09a52015-02-13 23:18:34 +0000350 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
351 ///
352 /// @{
353 /// \brief Recursively walk the \p DIE tree and look for DIEs to
354 /// keep. Store that information in \p CU's DIEInfo.
355 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
356 const DebugMapObject &DMO, CompileUnit &CU,
357 unsigned Flags);
358
359 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
360 enum TravesalFlags {
361 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
362 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
363 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
364 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
365 };
366
367 /// \brief Mark the passed DIE as well as all the ones it depends on
368 /// as kept.
369 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
370 CompileUnit::DIEInfo &MyInfo,
371 const DebugMapObject &DMO, CompileUnit &CU,
372 unsigned Flags);
373
374 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
375 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
376 unsigned Flags);
377
378 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
379 CompileUnit &Unit,
380 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
381
382 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
383 CompileUnit &Unit,
384 CompileUnit::DIEInfo &MyInfo,
385 unsigned Flags);
386
387 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
388 CompileUnit::DIEInfo &Info);
389 /// @}
390
Frederic Rissb8b43d52015-03-04 22:07:44 +0000391 /// \defgroup Linking Methods used to link the debug information
392 ///
393 /// @{
394 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
395 /// where useless (as decided by lookForDIEsToKeep()) bits have been
396 /// stripped out and addresses have been rewritten according to the
397 /// debug map.
398 ///
399 /// \param OutOffset is the offset the cloned DIE in the output
400 /// compile unit.
401 ///
402 /// \returns the root of the cloned tree.
403 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
404 uint32_t OutOffset);
405
406 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
407
408 /// \brief Helper for cloneDIE.
409 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
410 CompileUnit &U, const DWARFFormValue &Val,
411 const AttributeSpec AttrSpec, unsigned AttrSize);
412
413 /// \brief Helper for cloneDIE.
414 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec);
415
416 /// \brief Helper for cloneDIE.
417 unsigned cloneDieReferenceAttribute(DIE &Die, AttributeSpec AttrSpec,
418 unsigned AttrSize);
419
420 /// \brief Helper for cloneDIE.
421 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
422 const DWARFFormValue &Val, unsigned AttrSize);
423
424 /// \brief Helper for cloneDIE.
425 unsigned cloneScalarAttribute(DIE &Die,
426 const DWARFDebugInfoEntryMinimal &InputDIE,
427 const DWARFUnit &U, AttributeSpec AttrSpec,
428 const DWARFFormValue &Val, unsigned AttrSize);
429
430 /// \brief Assign an abbreviation number to \p Abbrev
431 void AssignAbbrev(DIEAbbrev &Abbrev);
432
433 /// \brief FoldingSet that uniques the abbreviations.
434 FoldingSet<DIEAbbrev> AbbreviationsSet;
435 /// \brief Storage for the unique Abbreviations.
436 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
437 /// be changed to a vecot of unique_ptrs.
438 std::vector<DIEAbbrev *> Abbreviations;
439
440 /// \brief DIELoc objects that need to be destructed (but not freed!).
441 std::vector<DIELoc *> DIELocs;
442 /// \brief DIEBlock objects that need to be destructed (but not freed!).
443 std::vector<DIEBlock *> DIEBlocks;
444 /// \brief Allocator used for all the DIEValue objects.
445 BumpPtrAllocator DIEAlloc;
446 /// @}
447
Frederic Riss1b9da422015-02-13 23:18:29 +0000448 /// \defgroup Helpers Various helper methods.
449 ///
450 /// @{
451 const DWARFDebugInfoEntryMinimal *
452 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
453 const DWARFDebugInfoEntryMinimal &DIE,
454 CompileUnit *&ReferencedCU);
455
456 CompileUnit *getUnitForOffset(unsigned Offset);
457
458 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
459 const DWARFDebugInfoEntryMinimal *DIE = nullptr);
Frederic Rissc99ea202015-02-28 00:29:11 +0000460
461 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +0000462 /// @}
463
Frederic Riss563cba62015-01-28 22:15:14 +0000464private:
Frederic Rissd3455182015-01-28 18:27:01 +0000465 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +0000466 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +0000467 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +0000468 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +0000469
470 /// The units of the current debug map object.
471 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +0000472
473 /// The debug map object curently under consideration.
474 DebugMapObject *CurrentDebugObject;
Frederic Rissd3455182015-01-28 18:27:01 +0000475};
476
Frederic Riss1b9da422015-02-13 23:18:29 +0000477/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
478/// returning our CompileUnit object instead.
479CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
480 auto CU =
481 std::upper_bound(Units.begin(), Units.end(), Offset,
482 [](uint32_t LHS, const CompileUnit &RHS) {
483 return LHS < RHS.getOrigUnit().getNextUnitOffset();
484 });
485 return CU != Units.end() ? &*CU : nullptr;
486}
487
488/// \brief Resolve the DIE attribute reference that has been
489/// extracted in \p RefValue. The resulting DIE migh be in another
490/// CompileUnit which is stored into \p ReferencedCU.
491/// \returns null if resolving fails for any reason.
492const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
493 DWARFFormValue &RefValue, const DWARFUnit &Unit,
494 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
495 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
496 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
497
498 if ((RefCU = getUnitForOffset(RefOffset)))
499 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
500 return RefDie;
501
502 reportWarning("could not find referenced DIE", &Unit, &DIE);
503 return nullptr;
504}
505
506/// \brief Report a warning to the user, optionaly including
507/// information about a specific \p DIE related to the warning.
508void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
509 const DWARFDebugInfoEntryMinimal *DIE) {
Frederic Rissdef4fb72015-02-28 00:29:01 +0000510 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +0000511 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +0000512 Context = CurrentDebugObject->getObjectFilename();
513 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +0000514
Frederic Rissb9818322015-02-28 00:29:07 +0000515 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +0000516 return;
517
518 errs() << " in DIE:\n";
519 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
520 6 /* Indent */);
521}
522
Frederic Rissc99ea202015-02-28 00:29:11 +0000523bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
524 if (Options.NoOutput)
525 return true;
526
Frederic Rissb52cf522015-02-28 00:42:37 +0000527 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +0000528 return Streamer->init(TheTriple, OutputFilename);
529}
530
Frederic Riss563cba62015-01-28 22:15:14 +0000531/// \brief Recursive helper to gather the child->parent relationships in the
532/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +0000533static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
534 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +0000535 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
536 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
537
538 if (DIE->hasChildren())
539 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
540 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +0000541 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +0000542}
543
Frederic Riss84c09a52015-02-13 23:18:34 +0000544static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
545 switch (Tag) {
546 default:
547 return false;
548 case dwarf::DW_TAG_subprogram:
549 case dwarf::DW_TAG_lexical_block:
550 case dwarf::DW_TAG_subroutine_type:
551 case dwarf::DW_TAG_structure_type:
552 case dwarf::DW_TAG_class_type:
553 case dwarf::DW_TAG_union_type:
554 return true;
555 }
556 llvm_unreachable("Invalid Tag");
557}
558
Frederic Riss563cba62015-01-28 22:15:14 +0000559void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
560 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +0000561 NextValidReloc = 0;
Frederic Riss563cba62015-01-28 22:15:14 +0000562}
563
Frederic Riss1036e642015-02-13 23:18:22 +0000564void DwarfLinker::endDebugObject() {
565 Units.clear();
566 ValidRelocs.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000567
568 for (auto *Block : DIEBlocks)
569 Block->~DIEBlock();
570 for (auto *Loc : DIELocs)
571 Loc->~DIELoc();
572
573 DIEBlocks.clear();
574 DIELocs.clear();
575 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +0000576}
577
578/// \brief Iterate over the relocations of the given \p Section and
579/// store the ones that correspond to debug map entries into the
580/// ValidRelocs array.
581void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
582 const object::MachOObjectFile &Obj,
583 const DebugMapObject &DMO) {
584 StringRef Contents;
585 Section.getContents(Contents);
586 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
587
588 for (const object::RelocationRef &Reloc : Section.relocations()) {
589 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
590 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
591 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
592 uint64_t Offset64;
593 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +0000594 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +0000595 continue;
596 }
597 uint32_t Offset = Offset64;
598 // Mach-o uses REL relocations, the addend is at the relocation offset.
599 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
600
601 auto Sym = Reloc.getSymbol();
602 if (Sym != Obj.symbol_end()) {
603 StringRef SymbolName;
604 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +0000605 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +0000606 continue;
607 }
608 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
609 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
610 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
611 // Do not store the addend. The addend was the address of the
612 // symbol in the object file, the address in the binary that is
613 // stored in the debug map doesn't need to be offseted.
614 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
615 }
616 }
617}
618
619/// \brief Dispatch the valid relocation finding logic to the
620/// appropriate handler depending on the object file format.
621bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
622 const object::ObjectFile &Obj,
623 const DebugMapObject &DMO) {
624 // Dispatch to the right handler depending on the file type.
625 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
626 findValidRelocsMachO(Section, *MachOObj, DMO);
627 else
Frederic Riss1b9da422015-02-13 23:18:29 +0000628 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +0000629
630 if (ValidRelocs.empty())
631 return false;
632
633 // Sort the relocations by offset. We will walk the DIEs linearly in
634 // the file, this allows us to just keep an index in the relocation
635 // array that we advance during our walk, rather than resorting to
636 // some associative container. See DwarfLinker::NextValidReloc.
637 std::sort(ValidRelocs.begin(), ValidRelocs.end());
638 return true;
639}
640
641/// \brief Look for relocations in the debug_info section that match
642/// entries in the debug map. These relocations will drive the Dwarf
643/// link by indicating which DIEs refer to symbols present in the
644/// linked binary.
645/// \returns wether there are any valid relocations in the debug info.
646bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
647 const DebugMapObject &DMO) {
648 // Find the debug_info section.
649 for (const object::SectionRef &Section : Obj.sections()) {
650 StringRef SectionName;
651 Section.getName(SectionName);
652 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
653 if (SectionName != "debug_info")
654 continue;
655 return findValidRelocs(Section, Obj, DMO);
656 }
657 return false;
658}
Frederic Riss563cba62015-01-28 22:15:14 +0000659
Frederic Riss84c09a52015-02-13 23:18:34 +0000660/// \brief Checks that there is a relocation against an actual debug
661/// map entry between \p StartOffset and \p NextOffset.
662///
663/// This function must be called with offsets in strictly ascending
664/// order because it never looks back at relocations it already 'went past'.
665/// \returns true and sets Info.InDebugMap if it is the case.
666bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
667 CompileUnit::DIEInfo &Info) {
668 assert(NextValidReloc == 0 ||
669 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
670 if (NextValidReloc >= ValidRelocs.size())
671 return false;
672
673 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
674
675 // We might need to skip some relocs that we didn't consider. For
676 // example the high_pc of a discarded DIE might contain a reloc that
677 // is in the list because it actually corresponds to the start of a
678 // function that is in the debug map.
679 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
680 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
681
682 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
683 return false;
684
685 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +0000686 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +0000687 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
688 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
689 ValidReloc.Mapping->getValue().ObjectAddress,
690 ValidReloc.Mapping->getValue().BinaryAddress);
691
692 Info.Address =
693 ValidReloc.Mapping->getValue().BinaryAddress + ValidReloc.Addend;
694 Info.InDebugMap = true;
695 return true;
696}
697
698/// \brief Get the starting and ending (exclusive) offset for the
699/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
700/// supposed to point to the position of the first attribute described
701/// by \p Abbrev.
702/// \return [StartOffset, EndOffset) as a pair.
703static std::pair<uint32_t, uint32_t>
704getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
705 unsigned Offset, const DWARFUnit &Unit) {
706 DataExtractor Data = Unit.getDebugInfoExtractor();
707
708 for (unsigned i = 0; i < Idx; ++i)
709 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
710
711 uint32_t End = Offset;
712 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
713
714 return std::make_pair(Offset, End);
715}
716
717/// \brief Check if a variable describing DIE should be kept.
718/// \returns updated TraversalFlags.
719unsigned DwarfLinker::shouldKeepVariableDIE(
720 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
721 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
722 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
723
724 // Global variables with constant value can always be kept.
725 if (!(Flags & TF_InFunctionScope) &&
726 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
727 MyInfo.InDebugMap = true;
728 return Flags | TF_Keep;
729 }
730
731 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
732 if (LocationIdx == -1U)
733 return Flags;
734
735 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
736 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
737 uint32_t LocationOffset, LocationEndOffset;
738 std::tie(LocationOffset, LocationEndOffset) =
739 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
740
741 // See if there is a relocation to a valid debug map entry inside
742 // this variable's location. The order is important here. We want to
743 // always check in the variable has a valid relocation, so that the
744 // DIEInfo is filled. However, we don't want a static variable in a
745 // function to force us to keep the enclosing function.
746 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
747 (Flags & TF_InFunctionScope))
748 return Flags;
749
Frederic Rissb9818322015-02-28 00:29:07 +0000750 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +0000751 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
752
753 return Flags | TF_Keep;
754}
755
756/// \brief Check if a function describing DIE should be kept.
757/// \returns updated TraversalFlags.
758unsigned DwarfLinker::shouldKeepSubprogramDIE(
759 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
760 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
761 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
762
763 Flags |= TF_InFunctionScope;
764
765 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
766 if (LowPcIdx == -1U)
767 return Flags;
768
769 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
770 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
771 uint32_t LowPcOffset, LowPcEndOffset;
772 std::tie(LowPcOffset, LowPcEndOffset) =
773 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
774
775 uint64_t LowPc =
776 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
777 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
778 if (LowPc == -1ULL ||
779 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
780 return Flags;
781
Frederic Rissb9818322015-02-28 00:29:07 +0000782 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +0000783 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
784
785 return Flags | TF_Keep;
786}
787
788/// \brief Check if a DIE should be kept.
789/// \returns updated TraversalFlags.
790unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
791 CompileUnit &Unit,
792 CompileUnit::DIEInfo &MyInfo,
793 unsigned Flags) {
794 switch (DIE.getTag()) {
795 case dwarf::DW_TAG_constant:
796 case dwarf::DW_TAG_variable:
797 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
798 case dwarf::DW_TAG_subprogram:
799 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
800 case dwarf::DW_TAG_module:
801 case dwarf::DW_TAG_imported_module:
802 case dwarf::DW_TAG_imported_declaration:
803 case dwarf::DW_TAG_imported_unit:
804 // We always want to keep these.
805 return Flags | TF_Keep;
806 }
807
808 return Flags;
809}
810
Frederic Riss84c09a52015-02-13 23:18:34 +0000811/// \brief Mark the passed DIE as well as all the ones it depends on
812/// as kept.
813///
814/// This function is called by lookForDIEsToKeep on DIEs that are
815/// newly discovered to be needed in the link. It recursively calls
816/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
817/// TraversalFlags to inform it that it's not doing the primary DIE
818/// tree walk.
819void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
820 CompileUnit::DIEInfo &MyInfo,
821 const DebugMapObject &DMO,
822 CompileUnit &CU, unsigned Flags) {
823 const DWARFUnit &Unit = CU.getOrigUnit();
824 MyInfo.Keep = true;
825
826 // First mark all the parent chain as kept.
827 unsigned AncestorIdx = MyInfo.ParentIdx;
828 while (!CU.getInfo(AncestorIdx).Keep) {
829 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
830 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
831 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
832 }
833
834 // Then we need to mark all the DIEs referenced by this DIE's
835 // attributes as kept.
836 DataExtractor Data = Unit.getDebugInfoExtractor();
837 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
838 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
839
840 // Mark all DIEs referenced through atttributes as kept.
841 for (const auto &AttrSpec : Abbrev->attributes()) {
842 DWARFFormValue Val(AttrSpec.Form);
843
844 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
845 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
846 continue;
847 }
848
849 Val.extractValue(Data, &Offset, &Unit);
850 CompileUnit *ReferencedCU;
851 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
852 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
853 TF_Keep | TF_DependencyWalk);
854 }
855}
856
857/// \brief Recursively walk the \p DIE tree and look for DIEs to
858/// keep. Store that information in \p CU's DIEInfo.
859///
860/// This function is the entry point of the DIE selection
861/// algorithm. It is expected to walk the DIE tree in file order and
862/// (though the mediation of its helper) call hasValidRelocation() on
863/// each DIE that might be a 'root DIE' (See DwarfLinker class
864/// comment).
865/// While walking the dependencies of root DIEs, this function is
866/// also called, but during these dependency walks the file order is
867/// not respected. The TF_DependencyWalk flag tells us which kind of
868/// traversal we are currently doing.
869void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
870 const DebugMapObject &DMO, CompileUnit &CU,
871 unsigned Flags) {
872 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
873 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
874 bool AlreadyKept = MyInfo.Keep;
875
876 // If the Keep flag is set, we are marking a required DIE's
877 // dependencies. If our target is already marked as kept, we're all
878 // set.
879 if ((Flags & TF_DependencyWalk) && AlreadyKept)
880 return;
881
882 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
883 // because it would screw up the relocation finding logic.
884 if (!(Flags & TF_DependencyWalk))
885 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
886
887 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
888 if (!AlreadyKept && (Flags & TF_Keep))
889 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
890
891 // The TF_ParentWalk flag tells us that we are currently walking up
892 // the parent chain of a required DIE, and we don't want to mark all
893 // the children of the parents as kept (consider for example a
894 // DW_TAG_namespace node in the parent chain). There are however a
895 // set of DIE types for which we want to ignore that directive and still
896 // walk their children.
897 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
898 Flags &= ~TF_ParentWalk;
899
900 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
901 return;
902
903 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
904 Child = Child->getSibling())
905 lookForDIEsToKeep(*Child, DMO, CU, Flags);
906}
907
Frederic Rissb8b43d52015-03-04 22:07:44 +0000908/// \brief Assign an abbreviation numer to \p Abbrev.
909///
910/// Our DIEs get freed after every DebugMapObject has been processed,
911/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
912/// the instances hold by the DIEs. When we encounter an abbreviation
913/// that we don't know, we create a permanent copy of it.
914void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
915 // Check the set for priors.
916 FoldingSetNodeID ID;
917 Abbrev.Profile(ID);
918 void *InsertToken;
919 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
920
921 // If it's newly added.
922 if (InSet) {
923 // Assign existing abbreviation number.
924 Abbrev.setNumber(InSet->getNumber());
925 } else {
926 // Add to abbreviation list.
927 Abbreviations.push_back(
928 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
929 for (const auto &Attr : Abbrev.getData())
930 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
931 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
932 // Assign the unique abbreviation number.
933 Abbrev.setNumber(Abbreviations.size());
934 Abbreviations.back()->setNumber(Abbreviations.size());
935 }
936}
937
938/// \brief Clone a string attribute described by \p AttrSpec and add
939/// it to \p Die.
940/// \returns the size of the new attribute.
941unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec) {
942 // Switch everything to out of line strings.
943 // FIXME: Construct the actual string table.
944 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
945 new (DIEAlloc) DIEInteger(0));
946 return 4;
947}
948
949/// \brief Clone an attribute referencing another DIE and add
950/// it to \p Die.
951/// \returns the size of the new attribute.
952unsigned DwarfLinker::cloneDieReferenceAttribute(DIE &Die,
953 AttributeSpec AttrSpec,
954 unsigned AttrSize) {
955 // FIXME: Handle DIE references.
956 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
957 new (DIEAlloc) DIEInteger(0));
958 return AttrSize;
959}
960
961/// \brief Clone an attribute of block form (locations, constants) and add
962/// it to \p Die.
963/// \returns the size of the new attribute.
964unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
965 const DWARFFormValue &Val,
966 unsigned AttrSize) {
967 DIE *Attr;
968 DIEValue *Value;
969 DIELoc *Loc = nullptr;
970 DIEBlock *Block = nullptr;
971 // Just copy the block data over.
972 if (AttrSpec.Attr == dwarf::DW_FORM_exprloc) {
973 Loc = new (DIEAlloc) DIELoc();
974 DIELocs.push_back(Loc);
975 } else {
976 Block = new (DIEAlloc) DIEBlock();
977 DIEBlocks.push_back(Block);
978 }
979 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
980 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
981 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
982 for (auto Byte : Bytes)
983 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
984 new (DIEAlloc) DIEInteger(Byte));
985 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
986 // the DIE class, this if could be replaced by
987 // Attr->setSize(Bytes.size()).
988 if (Streamer) {
989 if (Loc)
990 Loc->ComputeSize(&Streamer->getAsmPrinter());
991 else
992 Block->ComputeSize(&Streamer->getAsmPrinter());
993 }
994 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
995 Value);
996 return AttrSize;
997}
998
999/// \brief Clone a scalar attribute and add it to \p Die.
1000/// \returns the size of the new attribute.
1001unsigned DwarfLinker::cloneScalarAttribute(
1002 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, const DWARFUnit &U,
1003 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) {
1004 uint64_t Value;
1005 if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1006 Value = *Val.getAsSectionOffset();
1007 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1008 Value = *Val.getAsSignedConstant();
1009 else if (AttrSpec.Form == dwarf::DW_FORM_addr)
1010 Value = *Val.getAsAddress(&U);
1011 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1012 Value = *OptionalValue;
1013 else {
1014 reportWarning("Unsupported scalar attribute form. Dropping attribute.", &U,
1015 &InputDIE);
1016 return 0;
1017 }
1018 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1019 new (DIEAlloc) DIEInteger(Value));
1020 return AttrSize;
1021}
1022
1023/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1024/// value \p Val, and add it to \p Die.
1025/// \returns the size of the cloned attribute.
1026unsigned DwarfLinker::cloneAttribute(DIE &Die,
1027 const DWARFDebugInfoEntryMinimal &InputDIE,
1028 CompileUnit &Unit,
1029 const DWARFFormValue &Val,
1030 const AttributeSpec AttrSpec,
1031 unsigned AttrSize) {
1032 const DWARFUnit &U = Unit.getOrigUnit();
1033
1034 switch (AttrSpec.Form) {
1035 case dwarf::DW_FORM_strp:
1036 case dwarf::DW_FORM_string:
1037 return cloneStringAttribute(Die, AttrSpec);
1038 case dwarf::DW_FORM_ref_addr:
1039 case dwarf::DW_FORM_ref1:
1040 case dwarf::DW_FORM_ref2:
1041 case dwarf::DW_FORM_ref4:
1042 case dwarf::DW_FORM_ref8:
1043 return cloneDieReferenceAttribute(Die, AttrSpec, AttrSize);
1044 case dwarf::DW_FORM_block:
1045 case dwarf::DW_FORM_block1:
1046 case dwarf::DW_FORM_block2:
1047 case dwarf::DW_FORM_block4:
1048 case dwarf::DW_FORM_exprloc:
1049 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1050 case dwarf::DW_FORM_addr:
1051 case dwarf::DW_FORM_data1:
1052 case dwarf::DW_FORM_data2:
1053 case dwarf::DW_FORM_data4:
1054 case dwarf::DW_FORM_data8:
1055 case dwarf::DW_FORM_udata:
1056 case dwarf::DW_FORM_sdata:
1057 case dwarf::DW_FORM_sec_offset:
1058 case dwarf::DW_FORM_flag:
1059 case dwarf::DW_FORM_flag_present:
1060 return cloneScalarAttribute(Die, InputDIE, U, AttrSpec, Val, AttrSize);
1061 default:
1062 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1063 &InputDIE);
1064 }
1065
1066 return 0;
1067}
1068
1069/// \brief Recursively clone \p InputDIE's subtrees that have been
1070/// selected to appear in the linked output.
1071///
1072/// \param OutOffset is the Offset where the newly created DIE will
1073/// lie in the linked compile unit.
1074///
1075/// \returns the cloned DIE object or null if nothing was selected.
1076DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
1077 CompileUnit &Unit, uint32_t OutOffset) {
1078 DWARFUnit &U = Unit.getOrigUnit();
1079 unsigned Idx = U.getDIEIndex(&InputDIE);
1080
1081 // Should the DIE appear in the output?
1082 if (!Unit.getInfo(Idx).Keep)
1083 return nullptr;
1084
1085 uint32_t Offset = InputDIE.getOffset();
1086
1087 DIE *Die = new DIE(static_cast<dwarf::Tag>(InputDIE.getTag()));
1088 Die->setOffset(OutOffset);
1089
1090 // Extract and clone every attribute.
1091 DataExtractor Data = U.getDebugInfoExtractor();
1092 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1093 Offset += getULEB128Size(Abbrev->getCode());
1094
1095 for (const auto &AttrSpec : Abbrev->attributes()) {
1096 DWARFFormValue Val(AttrSpec.Form);
1097 uint32_t AttrSize = Offset;
1098 Val.extractValue(Data, &Offset, &U);
1099 AttrSize = Offset - AttrSize;
1100
1101 OutOffset += cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize);
1102 }
1103
1104 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1105 // If a scope DIE is kept, we must have kept at least one child. If
1106 // it's not the case, we'll just be emitting one wasteful end of
1107 // children marker, but things won't break.
1108 if (InputDIE.hasChildren())
1109 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1110 // Assign a permanent abbrev number
1111 AssignAbbrev(Die->getAbbrev());
1112
1113 // Add the size of the abbreviation number to the output offset.
1114 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1115
1116 if (!Abbrev->hasChildren()) {
1117 // Update our size.
1118 Die->setSize(OutOffset - Die->getOffset());
1119 return Die;
1120 }
1121
1122 // Recursively clone children.
1123 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1124 Child = Child->getSibling()) {
1125 if (DIE *Clone = cloneDIE(*Child, Unit, OutOffset)) {
1126 Die->addChild(std::unique_ptr<DIE>(Clone));
1127 OutOffset = Clone->getOffset() + Clone->getSize();
1128 }
1129 }
1130
1131 // Account for the end of children marker.
1132 OutOffset += sizeof(int8_t);
1133 // Update our size.
1134 Die->setSize(OutOffset - Die->getOffset());
1135 return Die;
1136}
1137
Frederic Rissd3455182015-01-28 18:27:01 +00001138bool DwarfLinker::link(const DebugMap &Map) {
1139
1140 if (Map.begin() == Map.end()) {
1141 errs() << "Empty debug map.\n";
1142 return false;
1143 }
1144
Frederic Rissc99ea202015-02-28 00:29:11 +00001145 if (!createStreamer(Map.getTriple(), OutputFilename))
1146 return false;
1147
Frederic Rissb8b43d52015-03-04 22:07:44 +00001148 // Size of the DIEs (and headers) generated for the linked output.
1149 uint64_t OutputDebugInfoSize = 0;
1150
Frederic Rissd3455182015-01-28 18:27:01 +00001151 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001152 CurrentDebugObject = Obj.get();
1153
Frederic Rissb9818322015-02-28 00:29:07 +00001154 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00001155 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1156 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1157 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001158 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00001159 continue;
1160 }
1161
Frederic Riss1036e642015-02-13 23:18:22 +00001162 // Look for relocations that correspond to debug map entries.
1163 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00001164 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00001165 outs() << "No valid relocations found. Skipping.\n";
1166 continue;
1167 }
1168
Frederic Riss563cba62015-01-28 22:15:14 +00001169 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00001170 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss563cba62015-01-28 22:15:14 +00001171 startDebugObject(DwarfContext);
Frederic Rissd3455182015-01-28 18:27:01 +00001172
Frederic Riss563cba62015-01-28 22:15:14 +00001173 // In a first phase, just read in the debug info and store the DIE
1174 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00001175 for (const auto &CU : DwarfContext.compile_units()) {
1176 auto *CUDie = CU->getCompileUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00001177 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00001178 outs() << "Input compilation unit:";
1179 CUDie->dump(outs(), CU.get(), 0);
1180 }
Frederic Riss563cba62015-01-28 22:15:14 +00001181 Units.emplace_back(*CU);
Frederic Riss9aa725b2015-02-13 23:18:31 +00001182 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00001183 }
Frederic Riss563cba62015-01-28 22:15:14 +00001184
Frederic Riss84c09a52015-02-13 23:18:34 +00001185 // Then mark all the DIEs that need to be present in the linked
1186 // output and collect some information about them. Note that this
1187 // loop can not be merged with the previous one becaue cross-cu
1188 // references require the ParentIdx to be setup for every CU in
1189 // the object file before calling this.
1190 for (auto &CurrentUnit : Units)
1191 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1192 CurrentUnit, 0);
1193
Frederic Rissb8b43d52015-03-04 22:07:44 +00001194 // Construct the output DIE tree by cloning the DIEs we chose to
1195 // keep above. If there are no valid relocs, then there's nothing
1196 // to clone/emit.
1197 if (!ValidRelocs.empty())
1198 for (auto &CurrentUnit : Units) {
1199 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
1200 DIE *OutputDIE =
1201 cloneDIE(*InputDIE, CurrentUnit, 11 /* Unit Header size */);
1202 CurrentUnit.setOutputUnitDIE(OutputDIE);
1203 OutputDebugInfoSize = CurrentUnit.computeOffsets(OutputDebugInfoSize);
1204 }
1205
1206 // Emit all the compile unit's debug information.
1207 if (!ValidRelocs.empty() && !Options.NoOutput)
1208 for (auto &CurrentUnit : Units) {
1209 Streamer->emitCompileUnitHeader(CurrentUnit);
1210 if (!CurrentUnit.getOutputUnitDIE())
1211 continue;
1212 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1213 }
1214
Frederic Riss563cba62015-01-28 22:15:14 +00001215 // Clean-up before starting working on the next object.
1216 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00001217 }
1218
Frederic Rissb8b43d52015-03-04 22:07:44 +00001219 // Emit everything that's global.
1220 if (!Options.NoOutput)
1221 Streamer->emitAbbrevs(Abbreviations);
1222
Frederic Rissc99ea202015-02-28 00:29:11 +00001223 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00001224}
1225}
Frederic Rissd3455182015-01-28 18:27:01 +00001226
Frederic Rissb9818322015-02-28 00:29:07 +00001227bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1228 const LinkOptions &Options) {
1229 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00001230 return Linker.link(DM);
1231}
1232}
Frederic Riss231f7142014-12-12 17:31:24 +00001233}