[dsymutil] Correctly clone address attributes.
[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     int64_t AddrAdjust; ///< Address offset to apply to 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   /// \param PCOffset (while cloning a function scope) is the offset
533   /// applied to the entry point of the function to get the linked address.
534   ///
535   /// \returns the root of the cloned tree.
536   DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
537                 int64_t PCOffset, uint32_t OutOffset);
538
539   typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
540
541   /// \brief Information gathered and exchanged between the various
542   /// clone*Attributes helpers about the attributes of a particular DIE.
543   struct AttributesInfo {
544     uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
545     int64_t PCOffset;    ///< Offset to apply to PC addresses inside a function.
546
547     AttributesInfo() : OrigHighPc(0), PCOffset(0) {}
548   };
549
550   /// \brief Helper for cloneDIE.
551   unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
552                           CompileUnit &U, const DWARFFormValue &Val,
553                           const AttributeSpec AttrSpec, unsigned AttrSize,
554                           AttributesInfo &AttrInfo);
555
556   /// \brief Helper for cloneDIE.
557   unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
558                                 const DWARFFormValue &Val, const DWARFUnit &U);
559
560   /// \brief Helper for cloneDIE.
561   unsigned
562   cloneDieReferenceAttribute(DIE &Die,
563                              const DWARFDebugInfoEntryMinimal &InputDIE,
564                              AttributeSpec AttrSpec, unsigned AttrSize,
565                              const DWARFFormValue &Val, const DWARFUnit &U);
566
567   /// \brief Helper for cloneDIE.
568   unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
569                                const DWARFFormValue &Val, unsigned AttrSize);
570
571   /// \brief Helper for cloneDIE.
572   unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
573                                  const DWARFFormValue &Val,
574                                  const CompileUnit &Unit, AttributesInfo &Info);
575
576   /// \brief Helper for cloneDIE.
577   unsigned cloneScalarAttribute(DIE &Die,
578                                 const DWARFDebugInfoEntryMinimal &InputDIE,
579                                 const DWARFUnit &U, AttributeSpec AttrSpec,
580                                 const DWARFFormValue &Val, unsigned AttrSize);
581
582   /// \brief Helper for cloneDIE.
583   bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
584                         bool isLittleEndian);
585
586   /// \brief Assign an abbreviation number to \p Abbrev
587   void AssignAbbrev(DIEAbbrev &Abbrev);
588
589   /// \brief FoldingSet that uniques the abbreviations.
590   FoldingSet<DIEAbbrev> AbbreviationsSet;
591   /// \brief Storage for the unique Abbreviations.
592   /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
593   /// be changed to a vecot of unique_ptrs.
594   std::vector<DIEAbbrev *> Abbreviations;
595
596   /// \brief DIELoc objects that need to be destructed (but not freed!).
597   std::vector<DIELoc *> DIELocs;
598   /// \brief DIEBlock objects that need to be destructed (but not freed!).
599   std::vector<DIEBlock *> DIEBlocks;
600   /// \brief Allocator used for all the DIEValue objects.
601   BumpPtrAllocator DIEAlloc;
602   /// @}
603
604   /// \defgroup Helpers Various helper methods.
605   ///
606   /// @{
607   const DWARFDebugInfoEntryMinimal *
608   resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
609                       const DWARFDebugInfoEntryMinimal &DIE,
610                       CompileUnit *&ReferencedCU);
611
612   CompileUnit *getUnitForOffset(unsigned Offset);
613
614   void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
615                      const DWARFDebugInfoEntryMinimal *DIE = nullptr);
616
617   bool createStreamer(Triple TheTriple, StringRef OutputFilename);
618   /// @}
619
620 private:
621   std::string OutputFilename;
622   LinkOptions Options;
623   BinaryHolder BinHolder;
624   std::unique_ptr<DwarfStreamer> Streamer;
625
626   /// The units of the current debug map object.
627   std::vector<CompileUnit> Units;
628
629   /// The debug map object curently under consideration.
630   DebugMapObject *CurrentDebugObject;
631
632   /// \brief The Dwarf string pool
633   NonRelocatableStringpool StringPool;
634 };
635
636 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
637 /// returning our CompileUnit object instead.
638 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
639   auto CU =
640       std::upper_bound(Units.begin(), Units.end(), Offset,
641                        [](uint32_t LHS, const CompileUnit &RHS) {
642                          return LHS < RHS.getOrigUnit().getNextUnitOffset();
643                        });
644   return CU != Units.end() ? &*CU : nullptr;
645 }
646
647 /// \brief Resolve the DIE attribute reference that has been
648 /// extracted in \p RefValue. The resulting DIE migh be in another
649 /// CompileUnit which is stored into \p ReferencedCU.
650 /// \returns null if resolving fails for any reason.
651 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
652     DWARFFormValue &RefValue, const DWARFUnit &Unit,
653     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
654   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
655   uint64_t RefOffset = *RefValue.getAsReference(&Unit);
656
657   if ((RefCU = getUnitForOffset(RefOffset)))
658     if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
659       return RefDie;
660
661   reportWarning("could not find referenced DIE", &Unit, &DIE);
662   return nullptr;
663 }
664
665 /// \brief Report a warning to the user, optionaly including
666 /// information about a specific \p DIE related to the warning.
667 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
668                                 const DWARFDebugInfoEntryMinimal *DIE) {
669   StringRef Context = "<debug map>";
670   if (CurrentDebugObject)
671     Context = CurrentDebugObject->getObjectFilename();
672   warn(Warning, Context);
673
674   if (!Options.Verbose || !DIE)
675     return;
676
677   errs() << "    in DIE:\n";
678   DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
679             6 /* Indent */);
680 }
681
682 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
683   if (Options.NoOutput)
684     return true;
685
686   Streamer = llvm::make_unique<DwarfStreamer>();
687   return Streamer->init(TheTriple, OutputFilename);
688 }
689
690 /// \brief Recursive helper to gather the child->parent relationships in the
691 /// original compile unit.
692 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
693                              unsigned ParentIdx, CompileUnit &CU) {
694   unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
695   CU.getInfo(MyIdx).ParentIdx = ParentIdx;
696
697   if (DIE->hasChildren())
698     for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
699          Child = Child->getSibling())
700       gatherDIEParents(Child, MyIdx, CU);
701 }
702
703 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
704   switch (Tag) {
705   default:
706     return false;
707   case dwarf::DW_TAG_subprogram:
708   case dwarf::DW_TAG_lexical_block:
709   case dwarf::DW_TAG_subroutine_type:
710   case dwarf::DW_TAG_structure_type:
711   case dwarf::DW_TAG_class_type:
712   case dwarf::DW_TAG_union_type:
713     return true;
714   }
715   llvm_unreachable("Invalid Tag");
716 }
717
718 void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
719   Units.reserve(Dwarf.getNumCompileUnits());
720   NextValidReloc = 0;
721 }
722
723 void DwarfLinker::endDebugObject() {
724   Units.clear();
725   ValidRelocs.clear();
726
727   for (auto *Block : DIEBlocks)
728     Block->~DIEBlock();
729   for (auto *Loc : DIELocs)
730     Loc->~DIELoc();
731
732   DIEBlocks.clear();
733   DIELocs.clear();
734   DIEAlloc.Reset();
735 }
736
737 /// \brief Iterate over the relocations of the given \p Section and
738 /// store the ones that correspond to debug map entries into the
739 /// ValidRelocs array.
740 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
741                                        const object::MachOObjectFile &Obj,
742                                        const DebugMapObject &DMO) {
743   StringRef Contents;
744   Section.getContents(Contents);
745   DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
746
747   for (const object::RelocationRef &Reloc : Section.relocations()) {
748     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
749     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
750     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
751     uint64_t Offset64;
752     if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
753       reportWarning(" unsupported relocation in debug_info section.");
754       continue;
755     }
756     uint32_t Offset = Offset64;
757     // Mach-o uses REL relocations, the addend is at the relocation offset.
758     uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
759
760     auto Sym = Reloc.getSymbol();
761     if (Sym != Obj.symbol_end()) {
762       StringRef SymbolName;
763       if (Sym->getName(SymbolName)) {
764         reportWarning("error getting relocation symbol name.");
765         continue;
766       }
767       if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
768         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
769     } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
770       // Do not store the addend. The addend was the address of the
771       // symbol in the object file, the address in the binary that is
772       // stored in the debug map doesn't need to be offseted.
773       ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
774     }
775   }
776 }
777
778 /// \brief Dispatch the valid relocation finding logic to the
779 /// appropriate handler depending on the object file format.
780 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
781                                   const object::ObjectFile &Obj,
782                                   const DebugMapObject &DMO) {
783   // Dispatch to the right handler depending on the file type.
784   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
785     findValidRelocsMachO(Section, *MachOObj, DMO);
786   else
787     reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
788
789   if (ValidRelocs.empty())
790     return false;
791
792   // Sort the relocations by offset. We will walk the DIEs linearly in
793   // the file, this allows us to just keep an index in the relocation
794   // array that we advance during our walk, rather than resorting to
795   // some associative container. See DwarfLinker::NextValidReloc.
796   std::sort(ValidRelocs.begin(), ValidRelocs.end());
797   return true;
798 }
799
800 /// \brief Look for relocations in the debug_info section that match
801 /// entries in the debug map. These relocations will drive the Dwarf
802 /// link by indicating which DIEs refer to symbols present in the
803 /// linked binary.
804 /// \returns wether there are any valid relocations in the debug info.
805 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
806                                              const DebugMapObject &DMO) {
807   // Find the debug_info section.
808   for (const object::SectionRef &Section : Obj.sections()) {
809     StringRef SectionName;
810     Section.getName(SectionName);
811     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
812     if (SectionName != "debug_info")
813       continue;
814     return findValidRelocs(Section, Obj, DMO);
815   }
816   return false;
817 }
818
819 /// \brief Checks that there is a relocation against an actual debug
820 /// map entry between \p StartOffset and \p NextOffset.
821 ///
822 /// This function must be called with offsets in strictly ascending
823 /// order because it never looks back at relocations it already 'went past'.
824 /// \returns true and sets Info.InDebugMap if it is the case.
825 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
826                                      CompileUnit::DIEInfo &Info) {
827   assert(NextValidReloc == 0 ||
828          StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
829   if (NextValidReloc >= ValidRelocs.size())
830     return false;
831
832   uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
833
834   // We might need to skip some relocs that we didn't consider. For
835   // example the high_pc of a discarded DIE might contain a reloc that
836   // is in the list because it actually corresponds to the start of a
837   // function that is in the debug map.
838   while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
839     RelocOffset = ValidRelocs[++NextValidReloc].Offset;
840
841   if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
842     return false;
843
844   const auto &ValidReloc = ValidRelocs[NextValidReloc++];
845   if (Options.Verbose)
846     outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
847            << " " << format("\t%016" PRIx64 " => %016" PRIx64,
848                             ValidReloc.Mapping->getValue().ObjectAddress,
849                             ValidReloc.Mapping->getValue().BinaryAddress);
850
851   Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
852                     ValidReloc.Addend -
853                     ValidReloc.Mapping->getValue().ObjectAddress;
854   Info.InDebugMap = true;
855   return true;
856 }
857
858 /// \brief Get the starting and ending (exclusive) offset for the
859 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
860 /// supposed to point to the position of the first attribute described
861 /// by \p Abbrev.
862 /// \return [StartOffset, EndOffset) as a pair.
863 static std::pair<uint32_t, uint32_t>
864 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
865                     unsigned Offset, const DWARFUnit &Unit) {
866   DataExtractor Data = Unit.getDebugInfoExtractor();
867
868   for (unsigned i = 0; i < Idx; ++i)
869     DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
870
871   uint32_t End = Offset;
872   DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
873
874   return std::make_pair(Offset, End);
875 }
876
877 /// \brief Check if a variable describing DIE should be kept.
878 /// \returns updated TraversalFlags.
879 unsigned DwarfLinker::shouldKeepVariableDIE(
880     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
881     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
882   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
883
884   // Global variables with constant value can always be kept.
885   if (!(Flags & TF_InFunctionScope) &&
886       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
887     MyInfo.InDebugMap = true;
888     return Flags | TF_Keep;
889   }
890
891   uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
892   if (LocationIdx == -1U)
893     return Flags;
894
895   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
896   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
897   uint32_t LocationOffset, LocationEndOffset;
898   std::tie(LocationOffset, LocationEndOffset) =
899       getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
900
901   // See if there is a relocation to a valid debug map entry inside
902   // this variable's location. The order is important here. We want to
903   // always check in the variable has a valid relocation, so that the
904   // DIEInfo is filled. However, we don't want a static variable in a
905   // function to force us to keep the enclosing function.
906   if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
907       (Flags & TF_InFunctionScope))
908     return Flags;
909
910   if (Options.Verbose)
911     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
912
913   return Flags | TF_Keep;
914 }
915
916 /// \brief Check if a function describing DIE should be kept.
917 /// \returns updated TraversalFlags.
918 unsigned DwarfLinker::shouldKeepSubprogramDIE(
919     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
920     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
921   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
922
923   Flags |= TF_InFunctionScope;
924
925   uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
926   if (LowPcIdx == -1U)
927     return Flags;
928
929   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
930   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
931   uint32_t LowPcOffset, LowPcEndOffset;
932   std::tie(LowPcOffset, LowPcEndOffset) =
933       getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
934
935   uint64_t LowPc =
936       DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
937   assert(LowPc != -1ULL && "low_pc attribute is not an address.");
938   if (LowPc == -1ULL ||
939       !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
940     return Flags;
941
942   if (Options.Verbose)
943     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
944
945   return Flags | TF_Keep;
946 }
947
948 /// \brief Check if a DIE should be kept.
949 /// \returns updated TraversalFlags.
950 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
951                                     CompileUnit &Unit,
952                                     CompileUnit::DIEInfo &MyInfo,
953                                     unsigned Flags) {
954   switch (DIE.getTag()) {
955   case dwarf::DW_TAG_constant:
956   case dwarf::DW_TAG_variable:
957     return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
958   case dwarf::DW_TAG_subprogram:
959     return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
960   case dwarf::DW_TAG_module:
961   case dwarf::DW_TAG_imported_module:
962   case dwarf::DW_TAG_imported_declaration:
963   case dwarf::DW_TAG_imported_unit:
964     // We always want to keep these.
965     return Flags | TF_Keep;
966   }
967
968   return Flags;
969 }
970
971 /// \brief Mark the passed DIE as well as all the ones it depends on
972 /// as kept.
973 ///
974 /// This function is called by lookForDIEsToKeep on DIEs that are
975 /// newly discovered to be needed in the link. It recursively calls
976 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
977 /// TraversalFlags to inform it that it's not doing the primary DIE
978 /// tree walk.
979 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
980                                           CompileUnit::DIEInfo &MyInfo,
981                                           const DebugMapObject &DMO,
982                                           CompileUnit &CU, unsigned Flags) {
983   const DWARFUnit &Unit = CU.getOrigUnit();
984   MyInfo.Keep = true;
985
986   // First mark all the parent chain as kept.
987   unsigned AncestorIdx = MyInfo.ParentIdx;
988   while (!CU.getInfo(AncestorIdx).Keep) {
989     lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
990                       TF_ParentWalk | TF_Keep | TF_DependencyWalk);
991     AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
992   }
993
994   // Then we need to mark all the DIEs referenced by this DIE's
995   // attributes as kept.
996   DataExtractor Data = Unit.getDebugInfoExtractor();
997   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
998   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
999
1000   // Mark all DIEs referenced through atttributes as kept.
1001   for (const auto &AttrSpec : Abbrev->attributes()) {
1002     DWARFFormValue Val(AttrSpec.Form);
1003
1004     if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1005       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1006       continue;
1007     }
1008
1009     Val.extractValue(Data, &Offset, &Unit);
1010     CompileUnit *ReferencedCU;
1011     if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1012       lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1013                         TF_Keep | TF_DependencyWalk);
1014   }
1015 }
1016
1017 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1018 /// keep. Store that information in \p CU's DIEInfo.
1019 ///
1020 /// This function is the entry point of the DIE selection
1021 /// algorithm. It is expected to walk the DIE tree in file order and
1022 /// (though the mediation of its helper) call hasValidRelocation() on
1023 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1024 /// comment).
1025 /// While walking the dependencies of root DIEs, this function is
1026 /// also called, but during these dependency walks the file order is
1027 /// not respected. The TF_DependencyWalk flag tells us which kind of
1028 /// traversal we are currently doing.
1029 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1030                                     const DebugMapObject &DMO, CompileUnit &CU,
1031                                     unsigned Flags) {
1032   unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1033   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1034   bool AlreadyKept = MyInfo.Keep;
1035
1036   // If the Keep flag is set, we are marking a required DIE's
1037   // dependencies. If our target is already marked as kept, we're all
1038   // set.
1039   if ((Flags & TF_DependencyWalk) && AlreadyKept)
1040     return;
1041
1042   // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1043   // because it would screw up the relocation finding logic.
1044   if (!(Flags & TF_DependencyWalk))
1045     Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1046
1047   // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1048   if (!AlreadyKept && (Flags & TF_Keep))
1049     keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1050
1051   // The TF_ParentWalk flag tells us that we are currently walking up
1052   // the parent chain of a required DIE, and we don't want to mark all
1053   // the children of the parents as kept (consider for example a
1054   // DW_TAG_namespace node in the parent chain). There are however a
1055   // set of DIE types for which we want to ignore that directive and still
1056   // walk their children.
1057   if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1058     Flags &= ~TF_ParentWalk;
1059
1060   if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1061     return;
1062
1063   for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1064        Child = Child->getSibling())
1065     lookForDIEsToKeep(*Child, DMO, CU, Flags);
1066 }
1067
1068 /// \brief Assign an abbreviation numer to \p Abbrev.
1069 ///
1070 /// Our DIEs get freed after every DebugMapObject has been processed,
1071 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1072 /// the instances hold by the DIEs. When we encounter an abbreviation
1073 /// that we don't know, we create a permanent copy of it.
1074 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1075   // Check the set for priors.
1076   FoldingSetNodeID ID;
1077   Abbrev.Profile(ID);
1078   void *InsertToken;
1079   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1080
1081   // If it's newly added.
1082   if (InSet) {
1083     // Assign existing abbreviation number.
1084     Abbrev.setNumber(InSet->getNumber());
1085   } else {
1086     // Add to abbreviation list.
1087     Abbreviations.push_back(
1088         new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1089     for (const auto &Attr : Abbrev.getData())
1090       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1091     AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1092     // Assign the unique abbreviation number.
1093     Abbrev.setNumber(Abbreviations.size());
1094     Abbreviations.back()->setNumber(Abbreviations.size());
1095   }
1096 }
1097
1098 /// \brief Clone a string attribute described by \p AttrSpec and add
1099 /// it to \p Die.
1100 /// \returns the size of the new attribute.
1101 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1102                                            const DWARFFormValue &Val,
1103                                            const DWARFUnit &U) {
1104   // Switch everything to out of line strings.
1105   const char *String = *Val.getAsCString(&U);
1106   unsigned Offset = StringPool.getStringOffset(String);
1107   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1108                new (DIEAlloc) DIEInteger(Offset));
1109   return 4;
1110 }
1111
1112 /// \brief Clone an attribute referencing another DIE and add
1113 /// it to \p Die.
1114 /// \returns the size of the new attribute.
1115 unsigned DwarfLinker::cloneDieReferenceAttribute(
1116     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1117     AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1118     const DWARFUnit &U) {
1119   uint32_t Ref = *Val.getAsReference(&U);
1120   DIE *NewRefDie = nullptr;
1121   CompileUnit *RefUnit = nullptr;
1122   const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1123
1124   if (!(RefUnit = getUnitForOffset(Ref)) ||
1125       !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1126     const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1127     if (!AttributeString)
1128       AttributeString = "DW_AT_???";
1129     reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1130                       ". Dropping.",
1131                   &U, &InputDIE);
1132     return 0;
1133   }
1134
1135   unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1136   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1137   if (!RefInfo.Clone) {
1138     assert(Ref > InputDIE.getOffset());
1139     // We haven't cloned this DIE yet. Just create an empty one and
1140     // store it. It'll get really cloned when we process it.
1141     RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1142   }
1143   NewRefDie = RefInfo.Clone;
1144
1145   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1146     // We cannot currently rely on a DIEEntry to emit ref_addr
1147     // references, because the implementation calls back to DwarfDebug
1148     // to find the unit offset. (We don't have a DwarfDebug)
1149     // FIXME: we should be able to design DIEEntry reliance on
1150     // DwarfDebug away.
1151     DIEInteger *Attr;
1152     if (Ref < InputDIE.getOffset()) {
1153       // We must have already cloned that DIE.
1154       uint32_t NewRefOffset =
1155           RefUnit->getStartOffset() + NewRefDie->getOffset();
1156       Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1157     } else {
1158       // A forward reference. Note and fixup later.
1159       Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
1160       RefUnit->noteForwardReference(NewRefDie, Attr);
1161     }
1162     Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1163                  Attr);
1164     return AttrSize;
1165   }
1166
1167   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1168                new (DIEAlloc) DIEEntry(*NewRefDie));
1169   return AttrSize;
1170 }
1171
1172 /// \brief Clone an attribute of block form (locations, constants) and add
1173 /// it to \p Die.
1174 /// \returns the size of the new attribute.
1175 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1176                                           const DWARFFormValue &Val,
1177                                           unsigned AttrSize) {
1178   DIE *Attr;
1179   DIEValue *Value;
1180   DIELoc *Loc = nullptr;
1181   DIEBlock *Block = nullptr;
1182   // Just copy the block data over.
1183   if (AttrSpec.Attr == dwarf::DW_FORM_exprloc) {
1184     Loc = new (DIEAlloc) DIELoc();
1185     DIELocs.push_back(Loc);
1186   } else {
1187     Block = new (DIEAlloc) DIEBlock();
1188     DIEBlocks.push_back(Block);
1189   }
1190   Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1191   Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1192   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1193   for (auto Byte : Bytes)
1194     Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1195                    new (DIEAlloc) DIEInteger(Byte));
1196   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1197   // the DIE class, this if could be replaced by
1198   // Attr->setSize(Bytes.size()).
1199   if (Streamer) {
1200     if (Loc)
1201       Loc->ComputeSize(&Streamer->getAsmPrinter());
1202     else
1203       Block->ComputeSize(&Streamer->getAsmPrinter());
1204   }
1205   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1206                Value);
1207   return AttrSize;
1208 }
1209
1210 /// \brief Clone an address attribute and add it to \p Die.
1211 /// \returns the size of the new attribute.
1212 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1213                                             const DWARFFormValue &Val,
1214                                             const CompileUnit &Unit,
1215                                             AttributesInfo &Info) {
1216   int64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1217   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1218     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1219         Die.getTag() == dwarf::DW_TAG_lexical_block)
1220       Addr += Info.PCOffset;
1221   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1222     // If we have a high_pc recorded for the input DIE, use
1223     // it. Otherwise (when no relocations where applied) just use the
1224     // one we just decoded.
1225     Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1226   }
1227
1228   Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1229                static_cast<dwarf::Form>(AttrSpec.Form),
1230                new (DIEAlloc) DIEInteger(Addr));
1231   return Unit.getOrigUnit().getAddressByteSize();
1232 }
1233
1234 /// \brief Clone a scalar attribute  and add it to \p Die.
1235 /// \returns the size of the new attribute.
1236 unsigned DwarfLinker::cloneScalarAttribute(
1237     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, const DWARFUnit &U,
1238     AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) {
1239   uint64_t Value;
1240   if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1241     Value = *Val.getAsSectionOffset();
1242   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1243     Value = *Val.getAsSignedConstant();
1244   else if (auto OptionalValue = Val.getAsUnsignedConstant())
1245     Value = *OptionalValue;
1246   else {
1247     reportWarning("Unsupported scalar attribute form. Dropping attribute.", &U,
1248                   &InputDIE);
1249     return 0;
1250   }
1251   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1252                new (DIEAlloc) DIEInteger(Value));
1253   return AttrSize;
1254 }
1255
1256 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1257 /// value \p Val, and add it to \p Die.
1258 /// \returns the size of the cloned attribute.
1259 unsigned DwarfLinker::cloneAttribute(DIE &Die,
1260                                      const DWARFDebugInfoEntryMinimal &InputDIE,
1261                                      CompileUnit &Unit,
1262                                      const DWARFFormValue &Val,
1263                                      const AttributeSpec AttrSpec,
1264                                      unsigned AttrSize, AttributesInfo &Info) {
1265   const DWARFUnit &U = Unit.getOrigUnit();
1266
1267   switch (AttrSpec.Form) {
1268   case dwarf::DW_FORM_strp:
1269   case dwarf::DW_FORM_string:
1270     return cloneStringAttribute(Die, AttrSpec, Val, U);
1271   case dwarf::DW_FORM_ref_addr:
1272   case dwarf::DW_FORM_ref1:
1273   case dwarf::DW_FORM_ref2:
1274   case dwarf::DW_FORM_ref4:
1275   case dwarf::DW_FORM_ref8:
1276     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1277                                       U);
1278   case dwarf::DW_FORM_block:
1279   case dwarf::DW_FORM_block1:
1280   case dwarf::DW_FORM_block2:
1281   case dwarf::DW_FORM_block4:
1282   case dwarf::DW_FORM_exprloc:
1283     return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1284   case dwarf::DW_FORM_addr:
1285     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1286   case dwarf::DW_FORM_data1:
1287   case dwarf::DW_FORM_data2:
1288   case dwarf::DW_FORM_data4:
1289   case dwarf::DW_FORM_data8:
1290   case dwarf::DW_FORM_udata:
1291   case dwarf::DW_FORM_sdata:
1292   case dwarf::DW_FORM_sec_offset:
1293   case dwarf::DW_FORM_flag:
1294   case dwarf::DW_FORM_flag_present:
1295     return cloneScalarAttribute(Die, InputDIE, U, AttrSpec, Val, AttrSize);
1296   default:
1297     reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1298                   &InputDIE);
1299   }
1300
1301   return 0;
1302 }
1303
1304 /// \brief Apply the valid relocations found by findValidRelocs() to
1305 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1306 /// in the debug_info section.
1307 ///
1308 /// Like for findValidRelocs(), this function must be called with
1309 /// monotonic \p BaseOffset values.
1310 ///
1311 /// \returns wether any reloc has been applied.
1312 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1313                                    uint32_t BaseOffset, bool isLittleEndian) {
1314   assert((NextValidReloc == 0 ||
1315          BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1316              "BaseOffset should only be increasing.");
1317   if (NextValidReloc >= ValidRelocs.size())
1318     return false;
1319
1320   // Skip relocs that haven't been applied.
1321   while (NextValidReloc < ValidRelocs.size() &&
1322          ValidRelocs[NextValidReloc].Offset < BaseOffset)
1323     ++NextValidReloc;
1324
1325   bool Applied = false;
1326   uint64_t EndOffset = BaseOffset + Data.size();
1327   while (NextValidReloc < ValidRelocs.size() &&
1328          ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1329          ValidRelocs[NextValidReloc].Offset < EndOffset) {
1330     const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1331     assert(ValidReloc.Offset - BaseOffset < Data.size());
1332     assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1333     char Buf[8];
1334     uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1335     Value += ValidReloc.Addend;
1336     for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1337       unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1338       Buf[i] = uint8_t(Value >> (Index * 8));
1339     }
1340     assert(ValidReloc.Size <= sizeof(Buf));
1341     memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1342     Applied = true;
1343   }
1344
1345   return Applied;
1346 }
1347
1348 /// \brief Recursively clone \p InputDIE's subtrees that have been
1349 /// selected to appear in the linked output.
1350 ///
1351 /// \param OutOffset is the Offset where the newly created DIE will
1352 /// lie in the linked compile unit.
1353 ///
1354 /// \returns the cloned DIE object or null if nothing was selected.
1355 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
1356                            CompileUnit &Unit, int64_t PCOffset,
1357                            uint32_t OutOffset) {
1358   DWARFUnit &U = Unit.getOrigUnit();
1359   unsigned Idx = U.getDIEIndex(&InputDIE);
1360   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1361
1362   // Should the DIE appear in the output?
1363   if (!Unit.getInfo(Idx).Keep)
1364     return nullptr;
1365
1366   uint32_t Offset = InputDIE.getOffset();
1367   // The DIE might have been already created by a forward reference
1368   // (see cloneDieReferenceAttribute()).
1369   DIE *Die = Info.Clone;
1370   if (!Die)
1371     Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1372   assert(Die->getTag() == InputDIE.getTag());
1373   Die->setOffset(OutOffset);
1374
1375   // Extract and clone every attribute.
1376   DataExtractor Data = U.getDebugInfoExtractor();
1377   uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
1378   AttributesInfo AttrInfo;
1379
1380   // We could copy the data only if we need to aply a relocation to
1381   // it. After testing, it seems there is no performance downside to
1382   // doing the copy unconditionally, and it makes the code simpler.
1383   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1384   Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1385   // Modify the copy with relocated addresses.
1386   if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1387     // If we applied relocations, we store the value of high_pc that was
1388     // potentially stored in the input DIE. If high_pc is an address
1389     // (Dwarf version == 2), then it might have been relocated to a
1390     // totally unrelated value (because the end address in the object
1391     // file might be start address of another function which got moved
1392     // independantly by the linker). The computation of the actual
1393     // high_pc value is done in cloneAddressAttribute().
1394     AttrInfo.OrigHighPc =
1395         InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
1396   }
1397
1398   // Reset the Offset to 0 as we will be working on the local copy of
1399   // the data.
1400   Offset = 0;
1401
1402   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1403   Offset += getULEB128Size(Abbrev->getCode());
1404
1405   // We are entering a subprogram. Get and propagate the PCOffset.
1406   if (Die->getTag() == dwarf::DW_TAG_subprogram)
1407     PCOffset = Info.AddrAdjust;
1408   AttrInfo.PCOffset = PCOffset;
1409
1410   for (const auto &AttrSpec : Abbrev->attributes()) {
1411     DWARFFormValue Val(AttrSpec.Form);
1412     uint32_t AttrSize = Offset;
1413     Val.extractValue(Data, &Offset, &U);
1414     AttrSize = Offset - AttrSize;
1415
1416     OutOffset +=
1417         cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
1418   }
1419
1420   DIEAbbrev &NewAbbrev = Die->getAbbrev();
1421   // If a scope DIE is kept, we must have kept at least one child. If
1422   // it's not the case, we'll just be emitting one wasteful end of
1423   // children marker, but things won't break.
1424   if (InputDIE.hasChildren())
1425     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1426   // Assign a permanent abbrev number
1427   AssignAbbrev(Die->getAbbrev());
1428
1429   // Add the size of the abbreviation number to the output offset.
1430   OutOffset += getULEB128Size(Die->getAbbrevNumber());
1431
1432   if (!Abbrev->hasChildren()) {
1433     // Update our size.
1434     Die->setSize(OutOffset - Die->getOffset());
1435     return Die;
1436   }
1437
1438   // Recursively clone children.
1439   for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1440        Child = Child->getSibling()) {
1441     if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
1442       Die->addChild(std::unique_ptr<DIE>(Clone));
1443       OutOffset = Clone->getOffset() + Clone->getSize();
1444     }
1445   }
1446
1447   // Account for the end of children marker.
1448   OutOffset += sizeof(int8_t);
1449   // Update our size.
1450   Die->setSize(OutOffset - Die->getOffset());
1451   return Die;
1452 }
1453
1454 bool DwarfLinker::link(const DebugMap &Map) {
1455
1456   if (Map.begin() == Map.end()) {
1457     errs() << "Empty debug map.\n";
1458     return false;
1459   }
1460
1461   if (!createStreamer(Map.getTriple(), OutputFilename))
1462     return false;
1463
1464   // Size of the DIEs (and headers) generated for the linked output.
1465   uint64_t OutputDebugInfoSize = 0;
1466
1467   for (const auto &Obj : Map.objects()) {
1468     CurrentDebugObject = Obj.get();
1469
1470     if (Options.Verbose)
1471       outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1472     auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1473     if (std::error_code EC = ErrOrObj.getError()) {
1474       reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
1475       continue;
1476     }
1477
1478     // Look for relocations that correspond to debug map entries.
1479     if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
1480       if (Options.Verbose)
1481         outs() << "No valid relocations found. Skipping.\n";
1482       continue;
1483     }
1484
1485     // Setup access to the debug info.
1486     DWARFContextInMemory DwarfContext(*ErrOrObj);
1487     startDebugObject(DwarfContext);
1488
1489     // In a first phase, just read in the debug info and store the DIE
1490     // parent links that we will use during the next phase.
1491     for (const auto &CU : DwarfContext.compile_units()) {
1492       auto *CUDie = CU->getCompileUnitDIE(false);
1493       if (Options.Verbose) {
1494         outs() << "Input compilation unit:";
1495         CUDie->dump(outs(), CU.get(), 0);
1496       }
1497       Units.emplace_back(*CU);
1498       gatherDIEParents(CUDie, 0, Units.back());
1499     }
1500
1501     // Then mark all the DIEs that need to be present in the linked
1502     // output and collect some information about them. Note that this
1503     // loop can not be merged with the previous one becaue cross-cu
1504     // references require the ParentIdx to be setup for every CU in
1505     // the object file before calling this.
1506     for (auto &CurrentUnit : Units)
1507       lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1508                         CurrentUnit, 0);
1509
1510     // The calls to applyValidRelocs inside cloneDIE will walk the
1511     // reloc array again (in the same way findValidRelocsInDebugInfo()
1512     // did). We need to reset the NextValidReloc index to the beginning.
1513     NextValidReloc = 0;
1514
1515     // Construct the output DIE tree by cloning the DIEs we chose to
1516     // keep above. If there are no valid relocs, then there's nothing
1517     // to clone/emit.
1518     if (!ValidRelocs.empty())
1519       for (auto &CurrentUnit : Units) {
1520         const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
1521         CurrentUnit.setStartOffset(OutputDebugInfoSize);
1522         DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
1523                                   11 /* Unit Header size */);
1524         CurrentUnit.setOutputUnitDIE(OutputDIE);
1525         OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
1526       }
1527
1528     // Emit all the compile unit's debug information.
1529     if (!ValidRelocs.empty() && !Options.NoOutput)
1530       for (auto &CurrentUnit : Units) {
1531         CurrentUnit.fixupForwardReferences();
1532         Streamer->emitCompileUnitHeader(CurrentUnit);
1533         if (!CurrentUnit.getOutputUnitDIE())
1534           continue;
1535         Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1536       }
1537
1538     // Clean-up before starting working on the next object.
1539     endDebugObject();
1540   }
1541
1542   // Emit everything that's global.
1543   if (!Options.NoOutput) {
1544     Streamer->emitAbbrevs(Abbreviations);
1545     Streamer->emitStrings(StringPool);
1546   }
1547
1548   return Options.NoOutput ? true : Streamer->finish();
1549 }
1550 }
1551
1552 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1553                const LinkOptions &Options) {
1554   DwarfLinker Linker(OutputFilename, Options);
1555   return Linker.link(DM);
1556 }
1557 }
1558 }