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