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