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