[DWARF parser] Make DWARF parser more robust against missing compile/type units.
[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/IntervalMap.h"
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/DIE.h"
18 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
20 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCCodeEmitter.h"
25 #include "llvm/MC/MCDwarf.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCObjectFileInfo.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/Object/MachO.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include <string>
38 #include <tuple>
39
40 namespace llvm {
41 namespace dsymutil {
42
43 namespace {
44
45 void warn(const Twine &Warning, const Twine &Context) {
46   errs() << Twine("while processing ") + Context + ":\n";
47   errs() << Twine("warning: ") + Warning + "\n";
48 }
49
50 bool error(const Twine &Error, const Twine &Context) {
51   errs() << Twine("while processing ") + Context + ":\n";
52   errs() << Twine("error: ") + Error + "\n";
53   return false;
54 }
55
56 template <typename KeyT, typename ValT>
57 using HalfOpenIntervalMap =
58     IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
59                 IntervalMapHalfOpenInfo<KeyT>>;
60
61 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
62
63 /// \brief Stores all information relating to a compile unit, be it in
64 /// its original instance in the object file to its brand new cloned
65 /// and linked DIE tree.
66 class CompileUnit {
67 public:
68   /// \brief Information gathered about a DIE in the object file.
69   struct DIEInfo {
70     int64_t AddrAdjust; ///< Address offset to apply to the described entity.
71     DIE *Clone;         ///< Cloned version of that DIE.
72     uint32_t ParentIdx; ///< The index of this DIE's parent.
73     bool Keep;          ///< Is the DIE part of the linked output?
74     bool InDebugMap;    ///< Was this DIE's entity found in the map?
75   };
76
77   CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
78       : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
79         Ranges(RangeAlloc), UnitRangeAttribute(nullptr) {
80     Info.resize(OrigUnit.getNumDIEs());
81   }
82
83   CompileUnit(CompileUnit &&RHS)
84       : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
85         CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
86         NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
87     // The CompileUnit container has been 'reserve()'d with the right
88     // size. We cannot move the IntervalMap anyway.
89     llvm_unreachable("CompileUnits should not be moved.");
90   }
91
92   DWARFUnit &getOrigUnit() const { return OrigUnit; }
93
94   unsigned getUniqueID() const { return ID; }
95
96   DIE *getOutputUnitDIE() const { return CUDie.get(); }
97   void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
98
99   DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
100   const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
101
102   uint64_t getStartOffset() const { return StartOffset; }
103   uint64_t getNextUnitOffset() const { return NextUnitOffset; }
104   void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
105
106   uint64_t getLowPc() const { return LowPc; }
107   uint64_t getHighPc() const { return HighPc; }
108
109   DIEInteger *getUnitRangesAttribute() const { return UnitRangeAttribute; }
110   const FunctionIntervals &getFunctionRanges() const { return Ranges; }
111   const std::vector<DIEInteger *> &getRangesAttributes() const {
112     return RangeAttributes;
113   }
114
115   const std::vector<std::pair<DIEInteger *, int64_t>> &
116   getLocationAttributes() const {
117     return LocationAttributes;
118   }
119
120   /// \brief Compute the end offset for this unit. Must be
121   /// called after the CU's DIEs have been cloned.
122   /// \returns the next unit offset (which is also the current
123   /// debug_info section size).
124   uint64_t computeNextUnitOffset();
125
126   /// \brief Keep track of a forward reference to DIE \p Die in \p
127   /// RefUnit by \p Attr. The attribute should be fixed up later to
128   /// point to the absolute offset of \p Die in the debug_info section.
129   void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
130                             DIEInteger *Attr);
131
132   /// \brief Apply all fixups recored by noteForwardReference().
133   void fixupForwardReferences();
134
135   /// \brief Add a function range [\p LowPC, \p HighPC) that is
136   /// relocatad by applying offset \p PCOffset.
137   void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
138
139   /// \brief Keep track of a DW_AT_range attribute that we will need to
140   /// patch up later.
141   void noteRangeAttribute(const DIE &Die, DIEInteger *Attr);
142
143   /// \brief Keep track of a location attribute pointing to a location
144   /// list in the debug_loc section.
145   void noteLocationAttribute(DIEInteger *Attr, int64_t PcOffset);
146
147   /// \brief Add a name accelerator entry for \p Die with \p Name
148   /// which is stored in the string table at \p Offset.
149   void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
150                           bool SkipPubnamesSection = false);
151
152   /// \brief Add a type accelerator entry for \p Die with \p Name
153   /// which is stored in the string table at \p Offset.
154   void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
155
156   struct AccelInfo {
157     StringRef Name; ///< Name of the entry.
158     const DIE *Die; ///< DIE this entry describes.
159     uint32_t NameOffset; ///< Offset of Name in the string pool.
160     bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
161
162     AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
163               bool SkipPubSection = false)
164         : Name(Name), Die(Die), NameOffset(NameOffset),
165           SkipPubSection(SkipPubSection) {}
166   };
167
168   const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
169   const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
170
171 private:
172   DWARFUnit &OrigUnit;
173   unsigned ID;
174   std::vector<DIEInfo> Info;  ///< DIE info indexed by DIE index.
175   std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
176
177   uint64_t StartOffset;
178   uint64_t NextUnitOffset;
179
180   uint64_t LowPc;
181   uint64_t HighPc;
182
183   /// \brief A list of attributes to fixup with the absolute offset of
184   /// a DIE in the debug_info section.
185   ///
186   /// The offsets for the attributes in this array couldn't be set while
187   /// cloning because for cross-cu forward refences the target DIE's
188   /// offset isn't known you emit the reference attribute.
189   std::vector<std::tuple<DIE *, const CompileUnit *, DIEInteger *>>
190       ForwardDIEReferences;
191
192   FunctionIntervals::Allocator RangeAlloc;
193   /// \brief The ranges in that interval map are the PC ranges for
194   /// functions in this unit, associated with the PC offset to apply
195   /// to the addresses to get the linked address.
196   FunctionIntervals Ranges;
197
198   /// \brief DW_AT_ranges attributes to patch after we have gathered
199   /// all the unit's function addresses.
200   /// @{
201   std::vector<DIEInteger *> RangeAttributes;
202   DIEInteger *UnitRangeAttribute;
203   /// @}
204
205   /// \brief Location attributes that need to be transfered from th
206   /// original debug_loc section to the liked one. They are stored
207   /// along with the PC offset that is to be applied to their
208   /// function's address.
209   std::vector<std::pair<DIEInteger *, int64_t>> LocationAttributes;
210
211   /// \brief Accelerator entries for the unit, both for the pub*
212   /// sections and the apple* ones.
213   /// @{
214   std::vector<AccelInfo> Pubnames;
215   std::vector<AccelInfo> Pubtypes;
216   /// @}
217 };
218
219 uint64_t CompileUnit::computeNextUnitOffset() {
220   NextUnitOffset = StartOffset + 11 /* Header size */;
221   // The root DIE might be null, meaning that the Unit had nothing to
222   // contribute to the linked output. In that case, we will emit the
223   // unit header without any actual DIE.
224   if (CUDie)
225     NextUnitOffset += CUDie->getSize();
226   return NextUnitOffset;
227 }
228
229 /// \brief Keep track of a forward cross-cu reference from this unit
230 /// to \p Die that lives in \p RefUnit.
231 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
232                                        DIEInteger *Attr) {
233   ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
234 }
235
236 /// \brief Apply all fixups recorded by noteForwardReference().
237 void CompileUnit::fixupForwardReferences() {
238   for (const auto &Ref : ForwardDIEReferences) {
239     DIE *RefDie;
240     const CompileUnit *RefUnit;
241     DIEInteger *Attr;
242     std::tie(RefDie, RefUnit, Attr) = Ref;
243     Attr->setValue(RefDie->getOffset() + RefUnit->getStartOffset());
244   }
245 }
246
247 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
248                                    int64_t PcOffset) {
249   Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
250   this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
251   this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
252 }
253
254 void CompileUnit::noteRangeAttribute(const DIE &Die, DIEInteger *Attr) {
255   if (Die.getTag() != dwarf::DW_TAG_compile_unit)
256     RangeAttributes.push_back(Attr);
257   else
258     UnitRangeAttribute = Attr;
259 }
260
261 void CompileUnit::noteLocationAttribute(DIEInteger *Attr, int64_t PcOffset) {
262   LocationAttributes.emplace_back(Attr, PcOffset);
263 }
264
265 /// \brief Add a name accelerator entry for \p Die with \p Name
266 /// which is stored in the string table at \p Offset.
267 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
268                                      uint32_t Offset, bool SkipPubSection) {
269   Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
270 }
271
272 /// \brief Add a type accelerator entry for \p Die with \p Name
273 /// which is stored in the string table at \p Offset.
274 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
275                                      uint32_t Offset) {
276   Pubtypes.emplace_back(Name, Die, Offset, false);
277 }
278
279 /// \brief A string table that doesn't need relocations.
280 ///
281 /// We are doing a final link, no need for a string table that
282 /// has relocation entries for every reference to it. This class
283 /// provides this ablitity by just associating offsets with
284 /// strings.
285 class NonRelocatableStringpool {
286 public:
287   /// \brief Entries are stored into the StringMap and simply linked
288   /// together through the second element of this pair in order to
289   /// keep track of insertion order.
290   typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
291       MapTy;
292
293   NonRelocatableStringpool()
294       : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
295     // Legacy dsymutil puts an empty string at the start of the line
296     // table.
297     getStringOffset("");
298   }
299
300   /// \brief Get the offset of string \p S in the string table. This
301   /// can insert a new element or return the offset of a preexisitng
302   /// one.
303   uint32_t getStringOffset(StringRef S);
304
305   /// \brief Get permanent storage for \p S (but do not necessarily
306   /// emit \p S in the output section).
307   /// \returns The StringRef that points to permanent storage to use
308   /// in place of \p S.
309   StringRef internString(StringRef S);
310
311   // \brief Return the first entry of the string table.
312   const MapTy::MapEntryTy *getFirstEntry() const {
313     return getNextEntry(&Sentinel);
314   }
315
316   // \brief Get the entry following \p E in the string table or null
317   // if \p E was the last entry.
318   const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
319     return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
320   }
321
322   uint64_t getSize() { return CurrentEndOffset; }
323
324 private:
325   MapTy Strings;
326   uint32_t CurrentEndOffset;
327   MapTy::MapEntryTy Sentinel, *Last;
328 };
329
330 /// \brief Get the offset of string \p S in the string table. This
331 /// can insert a new element or return the offset of a preexisitng
332 /// one.
333 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
334   if (S.empty() && !Strings.empty())
335     return 0;
336
337   std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
338   MapTy::iterator It;
339   bool Inserted;
340
341   // A non-empty string can't be at offset 0, so if we have an entry
342   // with a 0 offset, it must be a previously interned string.
343   std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
344   if (Inserted || It->getValue().first == 0) {
345     // Set offset and chain at the end of the entries list.
346     It->getValue().first = CurrentEndOffset;
347     CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
348     Last->getValue().second = &*It;
349     Last = &*It;
350   }
351   return It->getValue().first;
352 }
353
354 /// \brief Put \p S into the StringMap so that it gets permanent
355 /// storage, but do not actually link it in the chain of elements
356 /// that go into the output section. A latter call to
357 /// getStringOffset() with the same string will chain it though.
358 StringRef NonRelocatableStringpool::internString(StringRef S) {
359   std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
360   auto InsertResult = Strings.insert(std::make_pair(S, Entry));
361   return InsertResult.first->getKey();
362 }
363
364 /// \brief The Dwarf streaming logic
365 ///
366 /// All interactions with the MC layer that is used to build the debug
367 /// information binary representation are handled in this class.
368 class DwarfStreamer {
369   /// \defgroup MCObjects MC layer objects constructed by the streamer
370   /// @{
371   std::unique_ptr<MCRegisterInfo> MRI;
372   std::unique_ptr<MCAsmInfo> MAI;
373   std::unique_ptr<MCObjectFileInfo> MOFI;
374   std::unique_ptr<MCContext> MC;
375   MCAsmBackend *MAB; // Owned by MCStreamer
376   std::unique_ptr<MCInstrInfo> MII;
377   std::unique_ptr<MCSubtargetInfo> MSTI;
378   MCCodeEmitter *MCE; // Owned by MCStreamer
379   MCStreamer *MS;     // Owned by AsmPrinter
380   std::unique_ptr<TargetMachine> TM;
381   std::unique_ptr<AsmPrinter> Asm;
382   /// @}
383
384   /// \brief the file we stream the linked Dwarf to.
385   std::unique_ptr<raw_fd_ostream> OutFile;
386
387   uint32_t RangesSectionSize;
388   uint32_t LocSectionSize;
389   uint32_t LineSectionSize;
390
391   /// \brief Emit the pubnames or pubtypes section contribution for \p
392   /// Unit into \p Sec. The data is provided in \p Names.
393   void emitPubSectionForUnit(const MCSection *Sec, StringRef Name,
394                              const CompileUnit &Unit,
395                              const std::vector<CompileUnit::AccelInfo> &Names);
396
397 public:
398   /// \brief Actually create the streamer and the ouptut file.
399   ///
400   /// This could be done directly in the constructor, but it feels
401   /// more natural to handle errors through return value.
402   bool init(Triple TheTriple, StringRef OutputFilename);
403
404   /// \brief Dump the file to the disk.
405   bool finish();
406
407   AsmPrinter &getAsmPrinter() const { return *Asm; }
408
409   /// \brief Set the current output section to debug_info and change
410   /// the MC Dwarf version to \p DwarfVersion.
411   void switchToDebugInfoSection(unsigned DwarfVersion);
412
413   /// \brief Emit the compilation unit header for \p Unit in the
414   /// debug_info section.
415   ///
416   /// As a side effect, this also switches the current Dwarf version
417   /// of the MC layer to the one of U.getOrigUnit().
418   void emitCompileUnitHeader(CompileUnit &Unit);
419
420   /// \brief Recursively emit the DIE tree rooted at \p Die.
421   void emitDIE(DIE &Die);
422
423   /// \brief Emit the abbreviation table \p Abbrevs to the
424   /// debug_abbrev section.
425   void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
426
427   /// \brief Emit the string table described by \p Pool.
428   void emitStrings(const NonRelocatableStringpool &Pool);
429
430   /// \brief Emit debug_ranges for \p FuncRange by translating the
431   /// original \p Entries.
432   void emitRangesEntries(
433       int64_t UnitPcOffset, uint64_t OrigLowPc,
434       FunctionIntervals::const_iterator FuncRange,
435       const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
436       unsigned AddressSize);
437
438   /// \brief Emit debug_aranges entries for \p Unit and if \p
439   /// DoRangesSection is true, also emit the debug_ranges entries for
440   /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
441   void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
442
443   uint32_t getRangesSectionSize() const { return RangesSectionSize; }
444
445   /// \brief Emit the debug_loc contribution for \p Unit by copying
446   /// the entries from \p Dwarf and offseting them. Update the
447   /// location attributes to point to the new entries.
448   void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
449
450   /// \brief Emit the line table described in \p Rows into the
451   /// debug_line section.
452   void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
453                             std::vector<DWARFDebugLine::Row> &Rows,
454                             unsigned AdddressSize);
455
456   uint32_t getLineSectionSize() const { return LineSectionSize; }
457
458   /// \brief Emit the .debug_pubnames contribution for \p Unit.
459   void emitPubNamesForUnit(const CompileUnit &Unit);
460
461   /// \brief Emit the .debug_pubtypes contribution for \p Unit.
462   void emitPubTypesForUnit(const CompileUnit &Unit);
463 };
464
465 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
466   std::string ErrorStr;
467   std::string TripleName;
468   StringRef Context = "dwarf streamer init";
469
470   // Get the target.
471   const Target *TheTarget =
472       TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
473   if (!TheTarget)
474     return error(ErrorStr, Context);
475   TripleName = TheTriple.getTriple();
476
477   // Create all the MC Objects.
478   MRI.reset(TheTarget->createMCRegInfo(TripleName));
479   if (!MRI)
480     return error(Twine("no register info for target ") + TripleName, Context);
481
482   MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
483   if (!MAI)
484     return error("no asm info for target " + TripleName, Context);
485
486   MOFI.reset(new MCObjectFileInfo);
487   MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
488   MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
489                              *MC);
490
491   MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
492   if (!MAB)
493     return error("no asm backend for target " + TripleName, Context);
494
495   MII.reset(TheTarget->createMCInstrInfo());
496   if (!MII)
497     return error("no instr info info for target " + TripleName, Context);
498
499   MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
500   if (!MSTI)
501     return error("no subtarget info for target " + TripleName, Context);
502
503   MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
504   if (!MCE)
505     return error("no code emitter for target " + TripleName, Context);
506
507   // Create the output file.
508   std::error_code EC;
509   OutFile =
510       llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
511   if (EC)
512     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
513
514   MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
515                                          *MSTI, false,
516                                          /*DWARFMustBeAtTheEnd*/ false);
517   if (!MS)
518     return error("no object streamer for target " + TripleName, Context);
519
520   // Finally create the AsmPrinter we'll use to emit the DIEs.
521   TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
522   if (!TM)
523     return error("no target machine for target " + TripleName, Context);
524
525   Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
526   if (!Asm)
527     return error("no asm printer for target " + TripleName, Context);
528
529   RangesSectionSize = 0;
530   LocSectionSize = 0;
531   LineSectionSize = 0;
532
533   return true;
534 }
535
536 bool DwarfStreamer::finish() {
537   MS->Finish();
538   return true;
539 }
540
541 /// \brief Set the current output section to debug_info and change
542 /// the MC Dwarf version to \p DwarfVersion.
543 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
544   MS->SwitchSection(MOFI->getDwarfInfoSection());
545   MC->setDwarfVersion(DwarfVersion);
546 }
547
548 /// \brief Emit the compilation unit header for \p Unit in the
549 /// debug_info section.
550 ///
551 /// A Dwarf scetion header is encoded as:
552 ///  uint32_t   Unit length (omiting this field)
553 ///  uint16_t   Version
554 ///  uint32_t   Abbreviation table offset
555 ///  uint8_t    Address size
556 ///
557 /// Leading to a total of 11 bytes.
558 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
559   unsigned Version = Unit.getOrigUnit().getVersion();
560   switchToDebugInfoSection(Version);
561
562   // Emit size of content not including length itself. The size has
563   // already been computed in CompileUnit::computeOffsets(). Substract
564   // 4 to that size to account for the length field.
565   Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
566   Asm->EmitInt16(Version);
567   // We share one abbreviations table across all units so it's always at the
568   // start of the section.
569   Asm->EmitInt32(0);
570   Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
571 }
572
573 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
574 /// for the linked Dwarf file.
575 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
576   MS->SwitchSection(MOFI->getDwarfAbbrevSection());
577   Asm->emitDwarfAbbrevs(Abbrevs);
578 }
579
580 /// \brief Recursively emit the DIE tree rooted at \p Die.
581 void DwarfStreamer::emitDIE(DIE &Die) {
582   MS->SwitchSection(MOFI->getDwarfInfoSection());
583   Asm->emitDwarfDIE(Die);
584 }
585
586 /// \brief Emit the debug_str section stored in \p Pool.
587 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
588   Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
589   for (auto *Entry = Pool.getFirstEntry(); Entry;
590        Entry = Pool.getNextEntry(Entry))
591     Asm->OutStreamer->EmitBytes(
592         StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
593 }
594
595 /// \brief Emit the debug_range section contents for \p FuncRange by
596 /// translating the original \p Entries. The debug_range section
597 /// format is totally trivial, consisting just of pairs of address
598 /// sized addresses describing the ranges.
599 void DwarfStreamer::emitRangesEntries(
600     int64_t UnitPcOffset, uint64_t OrigLowPc,
601     FunctionIntervals::const_iterator FuncRange,
602     const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
603     unsigned AddressSize) {
604   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
605
606   // Offset each range by the right amount.
607   int64_t PcOffset = FuncRange.value() + UnitPcOffset;
608   for (const auto &Range : Entries) {
609     if (Range.isBaseAddressSelectionEntry(AddressSize)) {
610       warn("unsupported base address selection operation",
611            "emitting debug_ranges");
612       break;
613     }
614     // Do not emit empty ranges.
615     if (Range.StartAddress == Range.EndAddress)
616       continue;
617
618     // All range entries should lie in the function range.
619     if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
620           Range.EndAddress + OrigLowPc <= FuncRange.stop()))
621       warn("inconsistent range data.", "emitting debug_ranges");
622     MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
623     MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
624     RangesSectionSize += 2 * AddressSize;
625   }
626
627   // Add the terminator entry.
628   MS->EmitIntValue(0, AddressSize);
629   MS->EmitIntValue(0, AddressSize);
630   RangesSectionSize += 2 * AddressSize;
631 }
632
633 /// \brief Emit the debug_aranges contribution of a unit and
634 /// if \p DoDebugRanges is true the debug_range contents for a
635 /// compile_unit level DW_AT_ranges attribute (Which are basically the
636 /// same thing with a different base address).
637 /// Just aggregate all the ranges gathered inside that unit.
638 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
639                                           bool DoDebugRanges) {
640   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
641   // Gather the ranges in a vector, so that we can simplify them. The
642   // IntervalMap will have coalesced the non-linked ranges, but here
643   // we want to coalesce the linked addresses.
644   std::vector<std::pair<uint64_t, uint64_t>> Ranges;
645   const auto &FunctionRanges = Unit.getFunctionRanges();
646   for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
647        Range != End; ++Range)
648     Ranges.push_back(std::make_pair(Range.start() + Range.value(),
649                                     Range.stop() + Range.value()));
650
651   // The object addresses where sorted, but again, the linked
652   // addresses might end up in a different order.
653   std::sort(Ranges.begin(), Ranges.end());
654
655   if (!Ranges.empty()) {
656     MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
657
658     MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
659     MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
660
661     unsigned HeaderSize =
662         sizeof(int32_t) + // Size of contents (w/o this field
663         sizeof(int16_t) + // DWARF ARange version number
664         sizeof(int32_t) + // Offset of CU in the .debug_info section
665         sizeof(int8_t) +  // Pointer Size (in bytes)
666         sizeof(int8_t);   // Segment Size (in bytes)
667
668     unsigned TupleSize = AddressSize * 2;
669     unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
670
671     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
672     Asm->OutStreamer->EmitLabel(BeginLabel);
673     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
674     Asm->EmitInt32(Unit.getStartOffset());     // Corresponding unit's offset
675     Asm->EmitInt8(AddressSize);                // Address size
676     Asm->EmitInt8(0);                          // Segment size
677
678     Asm->OutStreamer->EmitFill(Padding, 0x0);
679
680     for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
681          ++Range) {
682       uint64_t RangeStart = Range->first;
683       MS->EmitIntValue(RangeStart, AddressSize);
684       while ((Range + 1) != End && Range->second == (Range + 1)->first)
685         ++Range;
686       MS->EmitIntValue(Range->second - RangeStart, AddressSize);
687     }
688
689     // Emit terminator
690     Asm->OutStreamer->EmitIntValue(0, AddressSize);
691     Asm->OutStreamer->EmitIntValue(0, AddressSize);
692     Asm->OutStreamer->EmitLabel(EndLabel);
693   }
694
695   if (!DoDebugRanges)
696     return;
697
698   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
699   // Offset each range by the right amount.
700   int64_t PcOffset = -Unit.getLowPc();
701   // Emit coalesced ranges.
702   for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
703     MS->EmitIntValue(Range->first + PcOffset, AddressSize);
704     while (Range + 1 != End && Range->second == (Range + 1)->first)
705       ++Range;
706     MS->EmitIntValue(Range->second + PcOffset, AddressSize);
707     RangesSectionSize += 2 * AddressSize;
708   }
709
710   // Add the terminator entry.
711   MS->EmitIntValue(0, AddressSize);
712   MS->EmitIntValue(0, AddressSize);
713   RangesSectionSize += 2 * AddressSize;
714 }
715
716 /// \brief Emit location lists for \p Unit and update attribtues to
717 /// point to the new entries.
718 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
719                                          DWARFContext &Dwarf) {
720   const std::vector<std::pair<DIEInteger *, int64_t>> &Attributes =
721       Unit.getLocationAttributes();
722
723   if (Attributes.empty())
724     return;
725
726   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
727
728   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
729   const DWARFSection &InputSec = Dwarf.getLocSection();
730   DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
731   DWARFUnit &OrigUnit = Unit.getOrigUnit();
732   const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
733   int64_t UnitPcOffset = 0;
734   uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
735       &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
736   if (OrigLowPc != -1ULL)
737     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
738
739   for (const auto &Attr : Attributes) {
740     uint32_t Offset = Attr.first->getValue();
741     Attr.first->setValue(LocSectionSize);
742     // This is the quantity to add to the old location address to get
743     // the correct address for the new one.
744     int64_t LocPcOffset = Attr.second + UnitPcOffset;
745     while (Data.isValidOffset(Offset)) {
746       uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
747       uint64_t High = Data.getUnsigned(&Offset, AddressSize);
748       LocSectionSize += 2 * AddressSize;
749       if (Low == 0 && High == 0) {
750         Asm->OutStreamer->EmitIntValue(0, AddressSize);
751         Asm->OutStreamer->EmitIntValue(0, AddressSize);
752         break;
753       }
754       Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
755       Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
756       uint64_t Length = Data.getU16(&Offset);
757       Asm->OutStreamer->EmitIntValue(Length, 2);
758       // Just copy the bytes over.
759       Asm->OutStreamer->EmitBytes(
760           StringRef(InputSec.Data.substr(Offset, Length)));
761       Offset += Length;
762       LocSectionSize += Length + 2;
763     }
764   }
765 }
766
767 void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
768                                          unsigned MinInstLength,
769                                          std::vector<DWARFDebugLine::Row> &Rows,
770                                          unsigned PointerSize) {
771   // Switch to the section where the table will be emitted into.
772   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
773   MCSymbol *LineStartSym = MC->createTempSymbol();
774   MCSymbol *LineEndSym = MC->createTempSymbol();
775
776   // The first 4 bytes is the total length of the information for this
777   // compilation unit (not including these 4 bytes for the length).
778   Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
779   Asm->OutStreamer->EmitLabel(LineStartSym);
780   // Copy Prologue.
781   MS->EmitBytes(PrologueBytes);
782   LineSectionSize += PrologueBytes.size() + 4;
783
784   SmallString<128> EncodingBuffer;
785   raw_svector_ostream EncodingOS(EncodingBuffer);
786
787   if (Rows.empty()) {
788     // We only have the dummy entry, dsymutil emits an entry with a 0
789     // address in that case.
790     MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
791     MS->EmitBytes(EncodingOS.str());
792     LineSectionSize += EncodingBuffer.size();
793     MS->EmitLabel(LineEndSym);
794     return;
795   }
796
797   // Line table state machine fields
798   unsigned FileNum = 1;
799   unsigned LastLine = 1;
800   unsigned Column = 0;
801   unsigned IsStatement = 1;
802   unsigned Isa = 0;
803   uint64_t Address = -1ULL;
804
805   unsigned RowsSinceLastSequence = 0;
806
807   for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
808     auto &Row = Rows[Idx];
809
810     int64_t AddressDelta;
811     if (Address == -1ULL) {
812       MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
813       MS->EmitULEB128IntValue(PointerSize + 1);
814       MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
815       MS->EmitIntValue(Row.Address, PointerSize);
816       LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
817       AddressDelta = 0;
818     } else {
819       AddressDelta = (Row.Address - Address) / MinInstLength;
820     }
821
822     // FIXME: code copied and transfromed from
823     // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
824     // this code, but the current compatibility requirement with
825     // classic dsymutil makes it hard. Revisit that once this
826     // requirement is dropped.
827
828     if (FileNum != Row.File) {
829       FileNum = Row.File;
830       MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
831       MS->EmitULEB128IntValue(FileNum);
832       LineSectionSize += 1 + getULEB128Size(FileNum);
833     }
834     if (Column != Row.Column) {
835       Column = Row.Column;
836       MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
837       MS->EmitULEB128IntValue(Column);
838       LineSectionSize += 1 + getULEB128Size(Column);
839     }
840
841     // FIXME: We should handle the discriminator here, but dsymutil
842     // doesn' consider it, thus ignore it for now.
843
844     if (Isa != Row.Isa) {
845       Isa = Row.Isa;
846       MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
847       MS->EmitULEB128IntValue(Isa);
848       LineSectionSize += 1 + getULEB128Size(Isa);
849     }
850     if (IsStatement != Row.IsStmt) {
851       IsStatement = Row.IsStmt;
852       MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
853       LineSectionSize += 1;
854     }
855     if (Row.BasicBlock) {
856       MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
857       LineSectionSize += 1;
858     }
859
860     if (Row.PrologueEnd) {
861       MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
862       LineSectionSize += 1;
863     }
864
865     if (Row.EpilogueBegin) {
866       MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
867       LineSectionSize += 1;
868     }
869
870     int64_t LineDelta = int64_t(Row.Line) - LastLine;
871     if (!Row.EndSequence) {
872       MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
873       MS->EmitBytes(EncodingOS.str());
874       LineSectionSize += EncodingBuffer.size();
875       EncodingBuffer.resize(0);
876       EncodingOS.resync();
877       Address = Row.Address;
878       LastLine = Row.Line;
879       RowsSinceLastSequence++;
880     } else {
881       if (LineDelta) {
882         MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
883         MS->EmitSLEB128IntValue(LineDelta);
884         LineSectionSize += 1 + getSLEB128Size(LineDelta);
885       }
886       if (AddressDelta) {
887         MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
888         MS->EmitULEB128IntValue(AddressDelta);
889         LineSectionSize += 1 + getULEB128Size(AddressDelta);
890       }
891       MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
892       MS->EmitBytes(EncodingOS.str());
893       LineSectionSize += EncodingBuffer.size();
894       EncodingBuffer.resize(0);
895       EncodingOS.resync();
896       Address = -1ULL;
897       LastLine = FileNum = IsStatement = 1;
898       RowsSinceLastSequence = Column = Isa = 0;
899     }
900   }
901
902   if (RowsSinceLastSequence) {
903     MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
904     MS->EmitBytes(EncodingOS.str());
905     LineSectionSize += EncodingBuffer.size();
906     EncodingBuffer.resize(0);
907     EncodingOS.resync();
908   }
909
910   MS->EmitLabel(LineEndSym);
911 }
912
913 /// \brief Emit the pubnames or pubtypes section contribution for \p
914 /// Unit into \p Sec. The data is provided in \p Names.
915 void DwarfStreamer::emitPubSectionForUnit(
916     const MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
917     const std::vector<CompileUnit::AccelInfo> &Names) {
918   if (Names.empty())
919     return;
920
921   // Start the dwarf pubnames section.
922   Asm->OutStreamer->SwitchSection(Sec);
923   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
924   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
925
926   bool HeaderEmitted = false;
927   // Emit the pubnames for this compilation unit.
928   for (const auto &Name : Names) {
929     if (Name.SkipPubSection)
930       continue;
931
932     if (!HeaderEmitted) {
933       // Emit the header.
934       Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
935       Asm->OutStreamer->EmitLabel(BeginLabel);
936       Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
937       Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
938       Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
939       HeaderEmitted = true;
940     }
941     Asm->EmitInt32(Name.Die->getOffset());
942     Asm->OutStreamer->EmitBytes(
943         StringRef(Name.Name.data(), Name.Name.size() + 1));
944   }
945
946   if (!HeaderEmitted)
947     return;
948   Asm->EmitInt32(0); // End marker.
949   Asm->OutStreamer->EmitLabel(EndLabel);
950 }
951
952 /// \brief Emit .debug_pubnames for \p Unit.
953 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
954   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
955                         "names", Unit, Unit.getPubnames());
956 }
957
958 /// \brief Emit .debug_pubtypes for \p Unit.
959 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
960   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
961                         "types", Unit, Unit.getPubtypes());
962 }
963
964 /// \brief The core of the Dwarf linking logic.
965 ///
966 /// The link of the dwarf information from the object files will be
967 /// driven by the selection of 'root DIEs', which are DIEs that
968 /// describe variables or functions that are present in the linked
969 /// binary (and thus have entries in the debug map). All the debug
970 /// information that will be linked (the DIEs, but also the line
971 /// tables, ranges, ...) is derived from that set of root DIEs.
972 ///
973 /// The root DIEs are identified because they contain relocations that
974 /// correspond to a debug map entry at specific places (the low_pc for
975 /// a function, the location for a variable). These relocations are
976 /// called ValidRelocs in the DwarfLinker and are gathered as a very
977 /// first step when we start processing a DebugMapObject.
978 class DwarfLinker {
979 public:
980   DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
981       : OutputFilename(OutputFilename), Options(Options),
982         BinHolder(Options.Verbose) {}
983
984   ~DwarfLinker() {
985     for (auto *Abbrev : Abbreviations)
986       delete Abbrev;
987   }
988
989   /// \brief Link the contents of the DebugMap.
990   bool link(const DebugMap &);
991
992 private:
993   /// \brief Called at the start of a debug object link.
994   void startDebugObject(DWARFContext &, DebugMapObject &);
995
996   /// \brief Called at the end of a debug object link.
997   void endDebugObject();
998
999   /// \defgroup FindValidRelocations Translate debug map into a list
1000   /// of relevant relocations
1001   ///
1002   /// @{
1003   struct ValidReloc {
1004     uint32_t Offset;
1005     uint32_t Size;
1006     uint64_t Addend;
1007     const DebugMapObject::DebugMapEntry *Mapping;
1008
1009     ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1010                const DebugMapObject::DebugMapEntry *Mapping)
1011         : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1012
1013     bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1014   };
1015
1016   /// \brief The valid relocations for the current DebugMapObject.
1017   /// This vector is sorted by relocation offset.
1018   std::vector<ValidReloc> ValidRelocs;
1019
1020   /// \brief Index into ValidRelocs of the next relocation to
1021   /// consider. As we walk the DIEs in acsending file offset and as
1022   /// ValidRelocs is sorted by file offset, keeping this index
1023   /// uptodate is all we have to do to have a cheap lookup during the
1024   /// root DIE selection and during DIE cloning.
1025   unsigned NextValidReloc;
1026
1027   bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1028                                   const DebugMapObject &DMO);
1029
1030   bool findValidRelocs(const object::SectionRef &Section,
1031                        const object::ObjectFile &Obj,
1032                        const DebugMapObject &DMO);
1033
1034   void findValidRelocsMachO(const object::SectionRef &Section,
1035                             const object::MachOObjectFile &Obj,
1036                             const DebugMapObject &DMO);
1037   /// @}
1038
1039   /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1040   ///
1041   /// @{
1042   /// \brief Recursively walk the \p DIE tree and look for DIEs to
1043   /// keep. Store that information in \p CU's DIEInfo.
1044   void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1045                          const DebugMapObject &DMO, CompileUnit &CU,
1046                          unsigned Flags);
1047
1048   /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1049   enum TravesalFlags {
1050     TF_Keep = 1 << 0,            ///< Mark the traversed DIEs as kept.
1051     TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1052     TF_DependencyWalk = 1 << 2,  ///< Walking the dependencies of a kept DIE.
1053     TF_ParentWalk = 1 << 3,      ///< Walking up the parents of a kept DIE.
1054   };
1055
1056   /// \brief Mark the passed DIE as well as all the ones it depends on
1057   /// as kept.
1058   void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1059                                CompileUnit::DIEInfo &MyInfo,
1060                                const DebugMapObject &DMO, CompileUnit &CU,
1061                                unsigned Flags);
1062
1063   unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1064                          CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1065                          unsigned Flags);
1066
1067   unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1068                                  CompileUnit &Unit,
1069                                  CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1070
1071   unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1072                                    CompileUnit &Unit,
1073                                    CompileUnit::DIEInfo &MyInfo,
1074                                    unsigned Flags);
1075
1076   bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1077                           CompileUnit::DIEInfo &Info);
1078   /// @}
1079
1080   /// \defgroup Linking Methods used to link the debug information
1081   ///
1082   /// @{
1083   /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1084   /// where useless (as decided by lookForDIEsToKeep()) bits have been
1085   /// stripped out and addresses have been rewritten according to the
1086   /// debug map.
1087   ///
1088   /// \param OutOffset is the offset the cloned DIE in the output
1089   /// compile unit.
1090   /// \param PCOffset (while cloning a function scope) is the offset
1091   /// applied to the entry point of the function to get the linked address.
1092   ///
1093   /// \returns the root of the cloned tree.
1094   DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
1095                 int64_t PCOffset, uint32_t OutOffset);
1096
1097   typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1098
1099   /// \brief Information gathered and exchanged between the various
1100   /// clone*Attributes helpers about the attributes of a particular DIE.
1101   struct AttributesInfo {
1102     const char *Name, *MangledName;         ///< Names.
1103     uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1104
1105     uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1106     int64_t PCOffset;    ///< Offset to apply to PC addresses inside a function.
1107
1108     bool HasLowPc;      ///< Does the DIE have a low_pc attribute?
1109     bool IsDeclaration; ///< Is this DIE only a declaration?
1110
1111     AttributesInfo()
1112         : Name(nullptr), MangledName(nullptr), NameOffset(0),
1113           MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1114           IsDeclaration(false) {}
1115   };
1116
1117   /// \brief Helper for cloneDIE.
1118   unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1119                           CompileUnit &U, const DWARFFormValue &Val,
1120                           const AttributeSpec AttrSpec, unsigned AttrSize,
1121                           AttributesInfo &AttrInfo);
1122
1123   /// \brief Helper for cloneDIE.
1124   unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1125                                 const DWARFFormValue &Val, const DWARFUnit &U);
1126
1127   /// \brief Helper for cloneDIE.
1128   unsigned
1129   cloneDieReferenceAttribute(DIE &Die,
1130                              const DWARFDebugInfoEntryMinimal &InputDIE,
1131                              AttributeSpec AttrSpec, unsigned AttrSize,
1132                              const DWARFFormValue &Val, CompileUnit &Unit);
1133
1134   /// \brief Helper for cloneDIE.
1135   unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1136                                const DWARFFormValue &Val, unsigned AttrSize);
1137
1138   /// \brief Helper for cloneDIE.
1139   unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1140                                  const DWARFFormValue &Val,
1141                                  const CompileUnit &Unit, AttributesInfo &Info);
1142
1143   /// \brief Helper for cloneDIE.
1144   unsigned cloneScalarAttribute(DIE &Die,
1145                                 const DWARFDebugInfoEntryMinimal &InputDIE,
1146                                 CompileUnit &U, AttributeSpec AttrSpec,
1147                                 const DWARFFormValue &Val, unsigned AttrSize,
1148                                 AttributesInfo &Info);
1149
1150   /// \brief Helper for cloneDIE.
1151   bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1152                         bool isLittleEndian);
1153
1154   /// \brief Assign an abbreviation number to \p Abbrev
1155   void AssignAbbrev(DIEAbbrev &Abbrev);
1156
1157   /// \brief FoldingSet that uniques the abbreviations.
1158   FoldingSet<DIEAbbrev> AbbreviationsSet;
1159   /// \brief Storage for the unique Abbreviations.
1160   /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1161   /// be changed to a vecot of unique_ptrs.
1162   std::vector<DIEAbbrev *> Abbreviations;
1163
1164   /// \brief Compute and emit debug_ranges section for \p Unit, and
1165   /// patch the attributes referencing it.
1166   void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1167
1168   /// \brief Generate and emit the DW_AT_ranges attribute for a
1169   /// compile_unit if it had one.
1170   void generateUnitRanges(CompileUnit &Unit) const;
1171
1172   /// \brief Extract the line tables fromt he original dwarf, extract
1173   /// the relevant parts according to the linked function ranges and
1174   /// emit the result in the debug_line section.
1175   void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1176
1177   /// \brief Emit the accelerator entries for \p Unit.
1178   void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1179
1180   /// \brief DIELoc objects that need to be destructed (but not freed!).
1181   std::vector<DIELoc *> DIELocs;
1182   /// \brief DIEBlock objects that need to be destructed (but not freed!).
1183   std::vector<DIEBlock *> DIEBlocks;
1184   /// \brief Allocator used for all the DIEValue objects.
1185   BumpPtrAllocator DIEAlloc;
1186   /// @}
1187
1188   /// \defgroup Helpers Various helper methods.
1189   ///
1190   /// @{
1191   const DWARFDebugInfoEntryMinimal *
1192   resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1193                       const DWARFDebugInfoEntryMinimal &DIE,
1194                       CompileUnit *&ReferencedCU);
1195
1196   CompileUnit *getUnitForOffset(unsigned Offset);
1197
1198   bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1199                    AttributesInfo &Info);
1200
1201   void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1202                      const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1203
1204   bool createStreamer(Triple TheTriple, StringRef OutputFilename);
1205   /// @}
1206
1207 private:
1208   std::string OutputFilename;
1209   LinkOptions Options;
1210   BinaryHolder BinHolder;
1211   std::unique_ptr<DwarfStreamer> Streamer;
1212
1213   /// The units of the current debug map object.
1214   std::vector<CompileUnit> Units;
1215
1216   /// The debug map object curently under consideration.
1217   DebugMapObject *CurrentDebugObject;
1218
1219   /// \brief The Dwarf string pool
1220   NonRelocatableStringpool StringPool;
1221
1222   /// \brief This map is keyed by the entry PC of functions in that
1223   /// debug object and the associated value is a pair storing the
1224   /// corresponding end PC and the offset to apply to get the linked
1225   /// address.
1226   ///
1227   /// See startDebugObject() for a more complete description of its use.
1228   std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1229 };
1230
1231 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1232 /// returning our CompileUnit object instead.
1233 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1234   auto CU =
1235       std::upper_bound(Units.begin(), Units.end(), Offset,
1236                        [](uint32_t LHS, const CompileUnit &RHS) {
1237                          return LHS < RHS.getOrigUnit().getNextUnitOffset();
1238                        });
1239   return CU != Units.end() ? &*CU : nullptr;
1240 }
1241
1242 /// \brief Resolve the DIE attribute reference that has been
1243 /// extracted in \p RefValue. The resulting DIE migh be in another
1244 /// CompileUnit which is stored into \p ReferencedCU.
1245 /// \returns null if resolving fails for any reason.
1246 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1247     DWARFFormValue &RefValue, const DWARFUnit &Unit,
1248     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1249   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1250   uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1251
1252   if ((RefCU = getUnitForOffset(RefOffset)))
1253     if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1254       return RefDie;
1255
1256   reportWarning("could not find referenced DIE", &Unit, &DIE);
1257   return nullptr;
1258 }
1259
1260 /// \brief Get the potential name and mangled name for the entity
1261 /// described by \p Die and store them in \Info if they are not
1262 /// already there.
1263 /// \returns is a name was found.
1264 bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1265                               DWARFUnit &U, AttributesInfo &Info) {
1266   // FIXME: a bit wastefull as the first getName might return the
1267   // short name.
1268   if (!Info.MangledName &&
1269       (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1270     Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1271
1272   if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1273     Info.NameOffset = StringPool.getStringOffset(Info.Name);
1274
1275   return Info.Name || Info.MangledName;
1276 }
1277
1278 /// \brief Report a warning to the user, optionaly including
1279 /// information about a specific \p DIE related to the warning.
1280 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1281                                 const DWARFDebugInfoEntryMinimal *DIE) const {
1282   StringRef Context = "<debug map>";
1283   if (CurrentDebugObject)
1284     Context = CurrentDebugObject->getObjectFilename();
1285   warn(Warning, Context);
1286
1287   if (!Options.Verbose || !DIE)
1288     return;
1289
1290   errs() << "    in DIE:\n";
1291   DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1292             6 /* Indent */);
1293 }
1294
1295 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1296   if (Options.NoOutput)
1297     return true;
1298
1299   Streamer = llvm::make_unique<DwarfStreamer>();
1300   return Streamer->init(TheTriple, OutputFilename);
1301 }
1302
1303 /// \brief Recursive helper to gather the child->parent relationships in the
1304 /// original compile unit.
1305 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1306                              unsigned ParentIdx, CompileUnit &CU) {
1307   unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1308   CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1309
1310   if (DIE->hasChildren())
1311     for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1312          Child = Child->getSibling())
1313       gatherDIEParents(Child, MyIdx, CU);
1314 }
1315
1316 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1317   switch (Tag) {
1318   default:
1319     return false;
1320   case dwarf::DW_TAG_subprogram:
1321   case dwarf::DW_TAG_lexical_block:
1322   case dwarf::DW_TAG_subroutine_type:
1323   case dwarf::DW_TAG_structure_type:
1324   case dwarf::DW_TAG_class_type:
1325   case dwarf::DW_TAG_union_type:
1326     return true;
1327   }
1328   llvm_unreachable("Invalid Tag");
1329 }
1330
1331 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1332   Units.reserve(Dwarf.getNumCompileUnits());
1333   NextValidReloc = 0;
1334   // Iterate over the debug map entries and put all the ones that are
1335   // functions (because they have a size) into the Ranges map. This
1336   // map is very similar to the FunctionRanges that are stored in each
1337   // unit, with 2 notable differences:
1338   //  - obviously this one is global, while the other ones are per-unit.
1339   //  - this one contains not only the functions described in the DIE
1340   // tree, but also the ones that are only in the debug map.
1341   // The latter information is required to reproduce dsymutil's logic
1342   // while linking line tables. The cases where this information
1343   // matters look like bugs that need to be investigated, but for now
1344   // we need to reproduce dsymutil's behavior.
1345   // FIXME: Once we understood exactly if that information is needed,
1346   // maybe totally remove this (or try to use it to do a real
1347   // -gline-tables-only on Darwin.
1348   for (const auto &Entry : Obj.symbols()) {
1349     const auto &Mapping = Entry.getValue();
1350     if (Mapping.Size)
1351       Ranges[Mapping.ObjectAddress] = std::make_pair(
1352           Mapping.ObjectAddress + Mapping.Size,
1353           int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1354   }
1355 }
1356
1357 void DwarfLinker::endDebugObject() {
1358   Units.clear();
1359   ValidRelocs.clear();
1360   Ranges.clear();
1361
1362   for (auto *Block : DIEBlocks)
1363     Block->~DIEBlock();
1364   for (auto *Loc : DIELocs)
1365     Loc->~DIELoc();
1366
1367   DIEBlocks.clear();
1368   DIELocs.clear();
1369   DIEAlloc.Reset();
1370 }
1371
1372 /// \brief Iterate over the relocations of the given \p Section and
1373 /// store the ones that correspond to debug map entries into the
1374 /// ValidRelocs array.
1375 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1376                                        const object::MachOObjectFile &Obj,
1377                                        const DebugMapObject &DMO) {
1378   StringRef Contents;
1379   Section.getContents(Contents);
1380   DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1381
1382   for (const object::RelocationRef &Reloc : Section.relocations()) {
1383     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1384     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1385     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1386     uint64_t Offset64;
1387     if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
1388       reportWarning(" unsupported relocation in debug_info section.");
1389       continue;
1390     }
1391     uint32_t Offset = Offset64;
1392     // Mach-o uses REL relocations, the addend is at the relocation offset.
1393     uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1394
1395     auto Sym = Reloc.getSymbol();
1396     if (Sym != Obj.symbol_end()) {
1397       StringRef SymbolName;
1398       if (Sym->getName(SymbolName)) {
1399         reportWarning("error getting relocation symbol name.");
1400         continue;
1401       }
1402       if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1403         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1404     } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1405       // Do not store the addend. The addend was the address of the
1406       // symbol in the object file, the address in the binary that is
1407       // stored in the debug map doesn't need to be offseted.
1408       ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1409     }
1410   }
1411 }
1412
1413 /// \brief Dispatch the valid relocation finding logic to the
1414 /// appropriate handler depending on the object file format.
1415 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1416                                   const object::ObjectFile &Obj,
1417                                   const DebugMapObject &DMO) {
1418   // Dispatch to the right handler depending on the file type.
1419   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1420     findValidRelocsMachO(Section, *MachOObj, DMO);
1421   else
1422     reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
1423
1424   if (ValidRelocs.empty())
1425     return false;
1426
1427   // Sort the relocations by offset. We will walk the DIEs linearly in
1428   // the file, this allows us to just keep an index in the relocation
1429   // array that we advance during our walk, rather than resorting to
1430   // some associative container. See DwarfLinker::NextValidReloc.
1431   std::sort(ValidRelocs.begin(), ValidRelocs.end());
1432   return true;
1433 }
1434
1435 /// \brief Look for relocations in the debug_info section that match
1436 /// entries in the debug map. These relocations will drive the Dwarf
1437 /// link by indicating which DIEs refer to symbols present in the
1438 /// linked binary.
1439 /// \returns wether there are any valid relocations in the debug info.
1440 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1441                                              const DebugMapObject &DMO) {
1442   // Find the debug_info section.
1443   for (const object::SectionRef &Section : Obj.sections()) {
1444     StringRef SectionName;
1445     Section.getName(SectionName);
1446     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1447     if (SectionName != "debug_info")
1448       continue;
1449     return findValidRelocs(Section, Obj, DMO);
1450   }
1451   return false;
1452 }
1453
1454 /// \brief Checks that there is a relocation against an actual debug
1455 /// map entry between \p StartOffset and \p NextOffset.
1456 ///
1457 /// This function must be called with offsets in strictly ascending
1458 /// order because it never looks back at relocations it already 'went past'.
1459 /// \returns true and sets Info.InDebugMap if it is the case.
1460 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1461                                      CompileUnit::DIEInfo &Info) {
1462   assert(NextValidReloc == 0 ||
1463          StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1464   if (NextValidReloc >= ValidRelocs.size())
1465     return false;
1466
1467   uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1468
1469   // We might need to skip some relocs that we didn't consider. For
1470   // example the high_pc of a discarded DIE might contain a reloc that
1471   // is in the list because it actually corresponds to the start of a
1472   // function that is in the debug map.
1473   while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1474     RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1475
1476   if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1477     return false;
1478
1479   const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1480   if (Options.Verbose)
1481     outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1482            << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1483                             ValidReloc.Mapping->getValue().ObjectAddress,
1484                             ValidReloc.Mapping->getValue().BinaryAddress);
1485
1486   Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1487                     ValidReloc.Addend -
1488                     ValidReloc.Mapping->getValue().ObjectAddress;
1489   Info.InDebugMap = true;
1490   return true;
1491 }
1492
1493 /// \brief Get the starting and ending (exclusive) offset for the
1494 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1495 /// supposed to point to the position of the first attribute described
1496 /// by \p Abbrev.
1497 /// \return [StartOffset, EndOffset) as a pair.
1498 static std::pair<uint32_t, uint32_t>
1499 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1500                     unsigned Offset, const DWARFUnit &Unit) {
1501   DataExtractor Data = Unit.getDebugInfoExtractor();
1502
1503   for (unsigned i = 0; i < Idx; ++i)
1504     DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1505
1506   uint32_t End = Offset;
1507   DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1508
1509   return std::make_pair(Offset, End);
1510 }
1511
1512 /// \brief Check if a variable describing DIE should be kept.
1513 /// \returns updated TraversalFlags.
1514 unsigned DwarfLinker::shouldKeepVariableDIE(
1515     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1516     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1517   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1518
1519   // Global variables with constant value can always be kept.
1520   if (!(Flags & TF_InFunctionScope) &&
1521       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1522     MyInfo.InDebugMap = true;
1523     return Flags | TF_Keep;
1524   }
1525
1526   uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1527   if (LocationIdx == -1U)
1528     return Flags;
1529
1530   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1531   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1532   uint32_t LocationOffset, LocationEndOffset;
1533   std::tie(LocationOffset, LocationEndOffset) =
1534       getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1535
1536   // See if there is a relocation to a valid debug map entry inside
1537   // this variable's location. The order is important here. We want to
1538   // always check in the variable has a valid relocation, so that the
1539   // DIEInfo is filled. However, we don't want a static variable in a
1540   // function to force us to keep the enclosing function.
1541   if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1542       (Flags & TF_InFunctionScope))
1543     return Flags;
1544
1545   if (Options.Verbose)
1546     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1547
1548   return Flags | TF_Keep;
1549 }
1550
1551 /// \brief Check if a function describing DIE should be kept.
1552 /// \returns updated TraversalFlags.
1553 unsigned DwarfLinker::shouldKeepSubprogramDIE(
1554     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1555     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1556   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1557
1558   Flags |= TF_InFunctionScope;
1559
1560   uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1561   if (LowPcIdx == -1U)
1562     return Flags;
1563
1564   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1565   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1566   uint32_t LowPcOffset, LowPcEndOffset;
1567   std::tie(LowPcOffset, LowPcEndOffset) =
1568       getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1569
1570   uint64_t LowPc =
1571       DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1572   assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1573   if (LowPc == -1ULL ||
1574       !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1575     return Flags;
1576
1577   if (Options.Verbose)
1578     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1579
1580   Flags |= TF_Keep;
1581
1582   DWARFFormValue HighPcValue;
1583   if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1584     reportWarning("Function without high_pc. Range will be discarded.\n",
1585                   &OrigUnit, &DIE);
1586     return Flags;
1587   }
1588
1589   uint64_t HighPc;
1590   if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1591     HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1592   } else {
1593     assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1594     HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1595   }
1596
1597   // Replace the debug map range with a more accurate one.
1598   Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
1599   Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1600   return Flags;
1601 }
1602
1603 /// \brief Check if a DIE should be kept.
1604 /// \returns updated TraversalFlags.
1605 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1606                                     CompileUnit &Unit,
1607                                     CompileUnit::DIEInfo &MyInfo,
1608                                     unsigned Flags) {
1609   switch (DIE.getTag()) {
1610   case dwarf::DW_TAG_constant:
1611   case dwarf::DW_TAG_variable:
1612     return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1613   case dwarf::DW_TAG_subprogram:
1614     return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1615   case dwarf::DW_TAG_module:
1616   case dwarf::DW_TAG_imported_module:
1617   case dwarf::DW_TAG_imported_declaration:
1618   case dwarf::DW_TAG_imported_unit:
1619     // We always want to keep these.
1620     return Flags | TF_Keep;
1621   }
1622
1623   return Flags;
1624 }
1625
1626 /// \brief Mark the passed DIE as well as all the ones it depends on
1627 /// as kept.
1628 ///
1629 /// This function is called by lookForDIEsToKeep on DIEs that are
1630 /// newly discovered to be needed in the link. It recursively calls
1631 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1632 /// TraversalFlags to inform it that it's not doing the primary DIE
1633 /// tree walk.
1634 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1635                                           CompileUnit::DIEInfo &MyInfo,
1636                                           const DebugMapObject &DMO,
1637                                           CompileUnit &CU, unsigned Flags) {
1638   const DWARFUnit &Unit = CU.getOrigUnit();
1639   MyInfo.Keep = true;
1640
1641   // First mark all the parent chain as kept.
1642   unsigned AncestorIdx = MyInfo.ParentIdx;
1643   while (!CU.getInfo(AncestorIdx).Keep) {
1644     lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1645                       TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1646     AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1647   }
1648
1649   // Then we need to mark all the DIEs referenced by this DIE's
1650   // attributes as kept.
1651   DataExtractor Data = Unit.getDebugInfoExtractor();
1652   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1653   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1654
1655   // Mark all DIEs referenced through atttributes as kept.
1656   for (const auto &AttrSpec : Abbrev->attributes()) {
1657     DWARFFormValue Val(AttrSpec.Form);
1658
1659     if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1660       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1661       continue;
1662     }
1663
1664     Val.extractValue(Data, &Offset, &Unit);
1665     CompileUnit *ReferencedCU;
1666     if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1667       lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1668                         TF_Keep | TF_DependencyWalk);
1669   }
1670 }
1671
1672 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1673 /// keep. Store that information in \p CU's DIEInfo.
1674 ///
1675 /// This function is the entry point of the DIE selection
1676 /// algorithm. It is expected to walk the DIE tree in file order and
1677 /// (though the mediation of its helper) call hasValidRelocation() on
1678 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1679 /// comment).
1680 /// While walking the dependencies of root DIEs, this function is
1681 /// also called, but during these dependency walks the file order is
1682 /// not respected. The TF_DependencyWalk flag tells us which kind of
1683 /// traversal we are currently doing.
1684 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1685                                     const DebugMapObject &DMO, CompileUnit &CU,
1686                                     unsigned Flags) {
1687   unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1688   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1689   bool AlreadyKept = MyInfo.Keep;
1690
1691   // If the Keep flag is set, we are marking a required DIE's
1692   // dependencies. If our target is already marked as kept, we're all
1693   // set.
1694   if ((Flags & TF_DependencyWalk) && AlreadyKept)
1695     return;
1696
1697   // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1698   // because it would screw up the relocation finding logic.
1699   if (!(Flags & TF_DependencyWalk))
1700     Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1701
1702   // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1703   if (!AlreadyKept && (Flags & TF_Keep))
1704     keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1705
1706   // The TF_ParentWalk flag tells us that we are currently walking up
1707   // the parent chain of a required DIE, and we don't want to mark all
1708   // the children of the parents as kept (consider for example a
1709   // DW_TAG_namespace node in the parent chain). There are however a
1710   // set of DIE types for which we want to ignore that directive and still
1711   // walk their children.
1712   if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1713     Flags &= ~TF_ParentWalk;
1714
1715   if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1716     return;
1717
1718   for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1719        Child = Child->getSibling())
1720     lookForDIEsToKeep(*Child, DMO, CU, Flags);
1721 }
1722
1723 /// \brief Assign an abbreviation numer to \p Abbrev.
1724 ///
1725 /// Our DIEs get freed after every DebugMapObject has been processed,
1726 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1727 /// the instances hold by the DIEs. When we encounter an abbreviation
1728 /// that we don't know, we create a permanent copy of it.
1729 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1730   // Check the set for priors.
1731   FoldingSetNodeID ID;
1732   Abbrev.Profile(ID);
1733   void *InsertToken;
1734   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1735
1736   // If it's newly added.
1737   if (InSet) {
1738     // Assign existing abbreviation number.
1739     Abbrev.setNumber(InSet->getNumber());
1740   } else {
1741     // Add to abbreviation list.
1742     Abbreviations.push_back(
1743         new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1744     for (const auto &Attr : Abbrev.getData())
1745       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1746     AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1747     // Assign the unique abbreviation number.
1748     Abbrev.setNumber(Abbreviations.size());
1749     Abbreviations.back()->setNumber(Abbreviations.size());
1750   }
1751 }
1752
1753 /// \brief Clone a string attribute described by \p AttrSpec and add
1754 /// it to \p Die.
1755 /// \returns the size of the new attribute.
1756 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1757                                            const DWARFFormValue &Val,
1758                                            const DWARFUnit &U) {
1759   // Switch everything to out of line strings.
1760   const char *String = *Val.getAsCString(&U);
1761   unsigned Offset = StringPool.getStringOffset(String);
1762   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1763                new (DIEAlloc) DIEInteger(Offset));
1764   return 4;
1765 }
1766
1767 /// \brief Clone an attribute referencing another DIE and add
1768 /// it to \p Die.
1769 /// \returns the size of the new attribute.
1770 unsigned DwarfLinker::cloneDieReferenceAttribute(
1771     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1772     AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1773     CompileUnit &Unit) {
1774   uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
1775   DIE *NewRefDie = nullptr;
1776   CompileUnit *RefUnit = nullptr;
1777   const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1778
1779   if (!(RefUnit = getUnitForOffset(Ref)) ||
1780       !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1781     const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1782     if (!AttributeString)
1783       AttributeString = "DW_AT_???";
1784     reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1785                       ". Dropping.",
1786                   &Unit.getOrigUnit(), &InputDIE);
1787     return 0;
1788   }
1789
1790   unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1791   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1792   if (!RefInfo.Clone) {
1793     assert(Ref > InputDIE.getOffset());
1794     // We haven't cloned this DIE yet. Just create an empty one and
1795     // store it. It'll get really cloned when we process it.
1796     RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1797   }
1798   NewRefDie = RefInfo.Clone;
1799
1800   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1801     // We cannot currently rely on a DIEEntry to emit ref_addr
1802     // references, because the implementation calls back to DwarfDebug
1803     // to find the unit offset. (We don't have a DwarfDebug)
1804     // FIXME: we should be able to design DIEEntry reliance on
1805     // DwarfDebug away.
1806     DIEInteger *Attr;
1807     if (Ref < InputDIE.getOffset()) {
1808       // We must have already cloned that DIE.
1809       uint32_t NewRefOffset =
1810           RefUnit->getStartOffset() + NewRefDie->getOffset();
1811       Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1812     } else {
1813       // A forward reference. Note and fixup later.
1814       Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
1815       Unit.noteForwardReference(NewRefDie, RefUnit, Attr);
1816     }
1817     Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1818                  Attr);
1819     return AttrSize;
1820   }
1821
1822   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1823                new (DIEAlloc) DIEEntry(*NewRefDie));
1824   return AttrSize;
1825 }
1826
1827 /// \brief Clone an attribute of block form (locations, constants) and add
1828 /// it to \p Die.
1829 /// \returns the size of the new attribute.
1830 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1831                                           const DWARFFormValue &Val,
1832                                           unsigned AttrSize) {
1833   DIE *Attr;
1834   DIEValue *Value;
1835   DIELoc *Loc = nullptr;
1836   DIEBlock *Block = nullptr;
1837   // Just copy the block data over.
1838   if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1839     Loc = new (DIEAlloc) DIELoc();
1840     DIELocs.push_back(Loc);
1841   } else {
1842     Block = new (DIEAlloc) DIEBlock();
1843     DIEBlocks.push_back(Block);
1844   }
1845   Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1846   Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1847   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1848   for (auto Byte : Bytes)
1849     Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1850                    new (DIEAlloc) DIEInteger(Byte));
1851   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1852   // the DIE class, this if could be replaced by
1853   // Attr->setSize(Bytes.size()).
1854   if (Streamer) {
1855     if (Loc)
1856       Loc->ComputeSize(&Streamer->getAsmPrinter());
1857     else
1858       Block->ComputeSize(&Streamer->getAsmPrinter());
1859   }
1860   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1861                Value);
1862   return AttrSize;
1863 }
1864
1865 /// \brief Clone an address attribute and add it to \p Die.
1866 /// \returns the size of the new attribute.
1867 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1868                                             const DWARFFormValue &Val,
1869                                             const CompileUnit &Unit,
1870                                             AttributesInfo &Info) {
1871   uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1872   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1873     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1874         Die.getTag() == dwarf::DW_TAG_lexical_block)
1875       Addr += Info.PCOffset;
1876     else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1877       Addr = Unit.getLowPc();
1878       if (Addr == UINT64_MAX)
1879         return 0;
1880     }
1881     Info.HasLowPc = true;
1882   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1883     if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1884       if (uint64_t HighPc = Unit.getHighPc())
1885         Addr = HighPc;
1886       else
1887         return 0;
1888     } else
1889       // If we have a high_pc recorded for the input DIE, use
1890       // it. Otherwise (when no relocations where applied) just use the
1891       // one we just decoded.
1892       Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1893   }
1894
1895   Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1896                static_cast<dwarf::Form>(AttrSpec.Form),
1897                new (DIEAlloc) DIEInteger(Addr));
1898   return Unit.getOrigUnit().getAddressByteSize();
1899 }
1900
1901 /// \brief Clone a scalar attribute  and add it to \p Die.
1902 /// \returns the size of the new attribute.
1903 unsigned DwarfLinker::cloneScalarAttribute(
1904     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
1905     AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
1906     AttributesInfo &Info) {
1907   uint64_t Value;
1908   if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1909       Die.getTag() == dwarf::DW_TAG_compile_unit) {
1910     if (Unit.getLowPc() == -1ULL)
1911       return 0;
1912     // Dwarf >= 4 high_pc is an size, not an address.
1913     Value = Unit.getHighPc() - Unit.getLowPc();
1914   } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1915     Value = *Val.getAsSectionOffset();
1916   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1917     Value = *Val.getAsSignedConstant();
1918   else if (auto OptionalValue = Val.getAsUnsignedConstant())
1919     Value = *OptionalValue;
1920   else {
1921     reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1922                   &Unit.getOrigUnit(), &InputDIE);
1923     return 0;
1924   }
1925   DIEInteger *Attr = new (DIEAlloc) DIEInteger(Value);
1926   if (AttrSpec.Attr == dwarf::DW_AT_ranges)
1927     Unit.noteRangeAttribute(Die, Attr);
1928   // A more generic way to check for location attributes would be
1929   // nice, but it's very unlikely that any other attribute needs a
1930   // location list.
1931   else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1932            AttrSpec.Attr == dwarf::DW_AT_frame_base)
1933     Unit.noteLocationAttribute(Attr, Info.PCOffset);
1934   else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1935     Info.IsDeclaration = true;
1936
1937   Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1938                Attr);
1939   return AttrSize;
1940 }
1941
1942 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1943 /// value \p Val, and add it to \p Die.
1944 /// \returns the size of the cloned attribute.
1945 unsigned DwarfLinker::cloneAttribute(DIE &Die,
1946                                      const DWARFDebugInfoEntryMinimal &InputDIE,
1947                                      CompileUnit &Unit,
1948                                      const DWARFFormValue &Val,
1949                                      const AttributeSpec AttrSpec,
1950                                      unsigned AttrSize, AttributesInfo &Info) {
1951   const DWARFUnit &U = Unit.getOrigUnit();
1952
1953   switch (AttrSpec.Form) {
1954   case dwarf::DW_FORM_strp:
1955   case dwarf::DW_FORM_string:
1956     return cloneStringAttribute(Die, AttrSpec, Val, U);
1957   case dwarf::DW_FORM_ref_addr:
1958   case dwarf::DW_FORM_ref1:
1959   case dwarf::DW_FORM_ref2:
1960   case dwarf::DW_FORM_ref4:
1961   case dwarf::DW_FORM_ref8:
1962     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1963                                       Unit);
1964   case dwarf::DW_FORM_block:
1965   case dwarf::DW_FORM_block1:
1966   case dwarf::DW_FORM_block2:
1967   case dwarf::DW_FORM_block4:
1968   case dwarf::DW_FORM_exprloc:
1969     return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1970   case dwarf::DW_FORM_addr:
1971     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1972   case dwarf::DW_FORM_data1:
1973   case dwarf::DW_FORM_data2:
1974   case dwarf::DW_FORM_data4:
1975   case dwarf::DW_FORM_data8:
1976   case dwarf::DW_FORM_udata:
1977   case dwarf::DW_FORM_sdata:
1978   case dwarf::DW_FORM_sec_offset:
1979   case dwarf::DW_FORM_flag:
1980   case dwarf::DW_FORM_flag_present:
1981     return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
1982                                 Info);
1983   default:
1984     reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1985                   &InputDIE);
1986   }
1987
1988   return 0;
1989 }
1990
1991 /// \brief Apply the valid relocations found by findValidRelocs() to
1992 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1993 /// in the debug_info section.
1994 ///
1995 /// Like for findValidRelocs(), this function must be called with
1996 /// monotonic \p BaseOffset values.
1997 ///
1998 /// \returns wether any reloc has been applied.
1999 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2000                                    uint32_t BaseOffset, bool isLittleEndian) {
2001   assert((NextValidReloc == 0 ||
2002           BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2003          "BaseOffset should only be increasing.");
2004   if (NextValidReloc >= ValidRelocs.size())
2005     return false;
2006
2007   // Skip relocs that haven't been applied.
2008   while (NextValidReloc < ValidRelocs.size() &&
2009          ValidRelocs[NextValidReloc].Offset < BaseOffset)
2010     ++NextValidReloc;
2011
2012   bool Applied = false;
2013   uint64_t EndOffset = BaseOffset + Data.size();
2014   while (NextValidReloc < ValidRelocs.size() &&
2015          ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2016          ValidRelocs[NextValidReloc].Offset < EndOffset) {
2017     const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2018     assert(ValidReloc.Offset - BaseOffset < Data.size());
2019     assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2020     char Buf[8];
2021     uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2022     Value += ValidReloc.Addend;
2023     for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2024       unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2025       Buf[i] = uint8_t(Value >> (Index * 8));
2026     }
2027     assert(ValidReloc.Size <= sizeof(Buf));
2028     memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2029     Applied = true;
2030   }
2031
2032   return Applied;
2033 }
2034
2035 static bool isTypeTag(uint16_t Tag) {
2036   switch (Tag) {
2037   case dwarf::DW_TAG_array_type:
2038   case dwarf::DW_TAG_class_type:
2039   case dwarf::DW_TAG_enumeration_type:
2040   case dwarf::DW_TAG_pointer_type:
2041   case dwarf::DW_TAG_reference_type:
2042   case dwarf::DW_TAG_string_type:
2043   case dwarf::DW_TAG_structure_type:
2044   case dwarf::DW_TAG_subroutine_type:
2045   case dwarf::DW_TAG_typedef:
2046   case dwarf::DW_TAG_union_type:
2047   case dwarf::DW_TAG_ptr_to_member_type:
2048   case dwarf::DW_TAG_set_type:
2049   case dwarf::DW_TAG_subrange_type:
2050   case dwarf::DW_TAG_base_type:
2051   case dwarf::DW_TAG_const_type:
2052   case dwarf::DW_TAG_constant:
2053   case dwarf::DW_TAG_file_type:
2054   case dwarf::DW_TAG_namelist:
2055   case dwarf::DW_TAG_packed_type:
2056   case dwarf::DW_TAG_volatile_type:
2057   case dwarf::DW_TAG_restrict_type:
2058   case dwarf::DW_TAG_interface_type:
2059   case dwarf::DW_TAG_unspecified_type:
2060   case dwarf::DW_TAG_shared_type:
2061     return true;
2062   default:
2063     break;
2064   }
2065   return false;
2066 }
2067
2068 /// \brief Recursively clone \p InputDIE's subtrees that have been
2069 /// selected to appear in the linked output.
2070 ///
2071 /// \param OutOffset is the Offset where the newly created DIE will
2072 /// lie in the linked compile unit.
2073 ///
2074 /// \returns the cloned DIE object or null if nothing was selected.
2075 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
2076                            CompileUnit &Unit, int64_t PCOffset,
2077                            uint32_t OutOffset) {
2078   DWARFUnit &U = Unit.getOrigUnit();
2079   unsigned Idx = U.getDIEIndex(&InputDIE);
2080   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2081
2082   // Should the DIE appear in the output?
2083   if (!Unit.getInfo(Idx).Keep)
2084     return nullptr;
2085
2086   uint32_t Offset = InputDIE.getOffset();
2087   // The DIE might have been already created by a forward reference
2088   // (see cloneDieReferenceAttribute()).
2089   DIE *Die = Info.Clone;
2090   if (!Die)
2091     Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
2092   assert(Die->getTag() == InputDIE.getTag());
2093   Die->setOffset(OutOffset);
2094
2095   // Extract and clone every attribute.
2096   DataExtractor Data = U.getDebugInfoExtractor();
2097   uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
2098   AttributesInfo AttrInfo;
2099
2100   // We could copy the data only if we need to aply a relocation to
2101   // it. After testing, it seems there is no performance downside to
2102   // doing the copy unconditionally, and it makes the code simpler.
2103   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2104   Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2105   // Modify the copy with relocated addresses.
2106   if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2107     // If we applied relocations, we store the value of high_pc that was
2108     // potentially stored in the input DIE. If high_pc is an address
2109     // (Dwarf version == 2), then it might have been relocated to a
2110     // totally unrelated value (because the end address in the object
2111     // file might be start address of another function which got moved
2112     // independantly by the linker). The computation of the actual
2113     // high_pc value is done in cloneAddressAttribute().
2114     AttrInfo.OrigHighPc =
2115         InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2116   }
2117
2118   // Reset the Offset to 0 as we will be working on the local copy of
2119   // the data.
2120   Offset = 0;
2121
2122   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2123   Offset += getULEB128Size(Abbrev->getCode());
2124
2125   // We are entering a subprogram. Get and propagate the PCOffset.
2126   if (Die->getTag() == dwarf::DW_TAG_subprogram)
2127     PCOffset = Info.AddrAdjust;
2128   AttrInfo.PCOffset = PCOffset;
2129
2130   for (const auto &AttrSpec : Abbrev->attributes()) {
2131     DWARFFormValue Val(AttrSpec.Form);
2132     uint32_t AttrSize = Offset;
2133     Val.extractValue(Data, &Offset, &U);
2134     AttrSize = Offset - AttrSize;
2135
2136     OutOffset +=
2137         cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2138   }
2139
2140   // Look for accelerator entries.
2141   uint16_t Tag = InputDIE.getTag();
2142   // FIXME: This is slightly wrong. An inline_subroutine without a
2143   // low_pc, but with AT_ranges might be interesting to get into the
2144   // accelerator tables too. For now stick with dsymutil's behavior.
2145   if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2146       Tag != dwarf::DW_TAG_compile_unit &&
2147       getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2148     if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2149       Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2150                               AttrInfo.MangledNameOffset,
2151                               Tag == dwarf::DW_TAG_inlined_subroutine);
2152     if (AttrInfo.Name)
2153       Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2154                               Tag == dwarf::DW_TAG_inlined_subroutine);
2155   } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2156              getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2157     Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2158   }
2159
2160   DIEAbbrev &NewAbbrev = Die->getAbbrev();
2161   // If a scope DIE is kept, we must have kept at least one child. If
2162   // it's not the case, we'll just be emitting one wasteful end of
2163   // children marker, but things won't break.
2164   if (InputDIE.hasChildren())
2165     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2166   // Assign a permanent abbrev number
2167   AssignAbbrev(Die->getAbbrev());
2168
2169   // Add the size of the abbreviation number to the output offset.
2170   OutOffset += getULEB128Size(Die->getAbbrevNumber());
2171
2172   if (!Abbrev->hasChildren()) {
2173     // Update our size.
2174     Die->setSize(OutOffset - Die->getOffset());
2175     return Die;
2176   }
2177
2178   // Recursively clone children.
2179   for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2180        Child = Child->getSibling()) {
2181     if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
2182       Die->addChild(std::unique_ptr<DIE>(Clone));
2183       OutOffset = Clone->getOffset() + Clone->getSize();
2184     }
2185   }
2186
2187   // Account for the end of children marker.
2188   OutOffset += sizeof(int8_t);
2189   // Update our size.
2190   Die->setSize(OutOffset - Die->getOffset());
2191   return Die;
2192 }
2193
2194 /// \brief Patch the input object file relevant debug_ranges entries
2195 /// and emit them in the output file. Update the relevant attributes
2196 /// to point at the new entries.
2197 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2198                                      DWARFContext &OrigDwarf) const {
2199   DWARFDebugRangeList RangeList;
2200   const auto &FunctionRanges = Unit.getFunctionRanges();
2201   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2202   DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2203                                OrigDwarf.isLittleEndian(), AddressSize);
2204   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2205   DWARFUnit &OrigUnit = Unit.getOrigUnit();
2206   const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2207   uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2208       &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2209   // Ranges addresses are based on the unit's low_pc. Compute the
2210   // offset we need to apply to adapt to the the new unit's low_pc.
2211   int64_t UnitPcOffset = 0;
2212   if (OrigLowPc != -1ULL)
2213     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2214
2215   for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2216     uint32_t Offset = RangeAttribute->getValue();
2217     RangeAttribute->setValue(Streamer->getRangesSectionSize());
2218     RangeList.extract(RangeExtractor, &Offset);
2219     const auto &Entries = RangeList.getEntries();
2220     const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2221
2222     if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2223         First.StartAddress >= CurrRange.stop()) {
2224       CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2225       if (CurrRange == InvalidRange ||
2226           CurrRange.start() > First.StartAddress + OrigLowPc) {
2227         reportWarning("no mapping for range.");
2228         continue;
2229       }
2230     }
2231
2232     Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2233                                 AddressSize);
2234   }
2235 }
2236
2237 /// \brief Generate the debug_aranges entries for \p Unit and if the
2238 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2239 /// contribution for this attribute.
2240 /// FIXME: this could actually be done right in patchRangesForUnit,
2241 /// but for the sake of initial bit-for-bit compatibility with legacy
2242 /// dsymutil, we have to do it in a delayed pass.
2243 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2244   DIEInteger *Attr = Unit.getUnitRangesAttribute();
2245   if (Attr)
2246     Attr->setValue(Streamer->getRangesSectionSize());
2247   Streamer->emitUnitRangesEntries(Unit, Attr != nullptr);
2248 }
2249
2250 /// \brief Insert the new line info sequence \p Seq into the current
2251 /// set of already linked line info \p Rows.
2252 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2253                                std::vector<DWARFDebugLine::Row> &Rows) {
2254   if (Seq.empty())
2255     return;
2256
2257   if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2258     Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2259     Seq.clear();
2260     return;
2261   }
2262
2263   auto InsertPoint = std::lower_bound(
2264       Rows.begin(), Rows.end(), Seq.front(),
2265       [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2266         return LHS.Address < RHS.Address;
2267       });
2268
2269   // FIXME: this only removes the unneeded end_sequence if the
2270   // sequences have been inserted in order. using a global sort like
2271   // described in patchLineTableForUnit() and delaying the end_sequene
2272   // elimination to emitLineTableForUnit() we can get rid of all of them.
2273   if (InsertPoint != Rows.end() &&
2274       InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2275     *InsertPoint = Seq.front();
2276     Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2277   } else {
2278     Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2279   }
2280
2281   Seq.clear();
2282 }
2283
2284 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2285 /// recreate a relocated version of these for the address ranges that
2286 /// are present in the binary.
2287 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2288                                         DWARFContext &OrigDwarf) {
2289   const DWARFDebugInfoEntryMinimal *CUDie =
2290       Unit.getOrigUnit().getUnitDIE();
2291   uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2292       &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2293   if (StmtList == -1ULL)
2294     return;
2295
2296   // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2297   if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
2298     const auto &Abbrev = OutputDIE->getAbbrev().getData();
2299     auto Stmt = std::find_if(
2300         Abbrev.begin(), Abbrev.end(), [](const DIEAbbrevData &AbbrevData) {
2301           return AbbrevData.getAttribute() == dwarf::DW_AT_stmt_list;
2302         });
2303     assert(Stmt < Abbrev.end() && "Didn't find DW_AT_stmt_list in cloned DIE!");
2304     DIEInteger *StmtAttr =
2305         cast<DIEInteger>(OutputDIE->getValues()[Stmt - Abbrev.begin()]);
2306     StmtAttr->setValue(Streamer->getLineSectionSize());
2307   }
2308
2309   // Parse the original line info for the unit.
2310   DWARFDebugLine::LineTable LineTable;
2311   uint32_t StmtOffset = StmtList;
2312   StringRef LineData = OrigDwarf.getLineSection().Data;
2313   DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2314                               Unit.getOrigUnit().getAddressByteSize());
2315   LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2316                   &StmtOffset);
2317
2318   // This vector is the output line table.
2319   std::vector<DWARFDebugLine::Row> NewRows;
2320   NewRows.reserve(LineTable.Rows.size());
2321
2322   // Current sequence of rows being extracted, before being inserted
2323   // in NewRows.
2324   std::vector<DWARFDebugLine::Row> Seq;
2325   const auto &FunctionRanges = Unit.getFunctionRanges();
2326   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2327
2328   // FIXME: This logic is meant to generate exactly the same output as
2329   // Darwin's classic dsynutil. There is a nicer way to implement this
2330   // by simply putting all the relocated line info in NewRows and simply
2331   // sorting NewRows before passing it to emitLineTableForUnit. This
2332   // should be correct as sequences for a function should stay
2333   // together in the sorted output. There are a few corner cases that
2334   // look suspicious though, and that required to implement the logic
2335   // this way. Revisit that once initial validation is finished.
2336
2337   // Iterate over the object file line info and extract the sequences
2338   // that correspond to linked functions.
2339   for (auto &Row : LineTable.Rows) {
2340     // Check wether we stepped out of the range. The range is
2341     // half-open, but consider accept the end address of the range if
2342     // it is marked as end_sequence in the input (because in that
2343     // case, the relocation offset is accurate and that entry won't
2344     // serve as the start of another function).
2345     if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2346         Row.Address > CurrRange.stop() ||
2347         (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2348       // We just stepped out of a known range. Insert a end_sequence
2349       // corresponding to the end of the range.
2350       uint64_t StopAddress = CurrRange != InvalidRange
2351                                  ? CurrRange.stop() + CurrRange.value()
2352                                  : -1ULL;
2353       CurrRange = FunctionRanges.find(Row.Address);
2354       bool CurrRangeValid =
2355           CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2356       if (!CurrRangeValid) {
2357         CurrRange = InvalidRange;
2358         if (StopAddress != -1ULL) {
2359           // Try harder by looking in the DebugMapObject function
2360           // ranges map. There are corner cases where this finds a
2361           // valid entry. It's unclear if this is right or wrong, but
2362           // for now do as dsymutil.
2363           // FIXME: Understand exactly what cases this addresses and
2364           // potentially remove it along with the Ranges map.
2365           auto Range = Ranges.lower_bound(Row.Address);
2366           if (Range != Ranges.begin() && Range != Ranges.end())
2367             --Range;
2368
2369           if (Range != Ranges.end() && Range->first <= Row.Address &&
2370               Range->second.first >= Row.Address) {
2371             StopAddress = Row.Address + Range->second.second;
2372           }
2373         }
2374       }
2375       if (StopAddress != -1ULL && !Seq.empty()) {
2376         // Insert end sequence row with the computed end address, but
2377         // the same line as the previous one.
2378         Seq.emplace_back(Seq.back());
2379         Seq.back().Address = StopAddress;
2380         Seq.back().EndSequence = 1;
2381         Seq.back().PrologueEnd = 0;
2382         Seq.back().BasicBlock = 0;
2383         Seq.back().EpilogueBegin = 0;
2384         insertLineSequence(Seq, NewRows);
2385       }
2386
2387       if (!CurrRangeValid)
2388         continue;
2389     }
2390
2391     // Ignore empty sequences.
2392     if (Row.EndSequence && Seq.empty())
2393       continue;
2394
2395     // Relocate row address and add it to the current sequence.
2396     Row.Address += CurrRange.value();
2397     Seq.emplace_back(Row);
2398
2399     if (Row.EndSequence)
2400       insertLineSequence(Seq, NewRows);
2401   }
2402
2403   // Finished extracting, now emit the line tables.
2404   uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2405   // FIXME: LLVM hardcodes it's prologue values. We just copy the
2406   // prologue over and that works because we act as both producer and
2407   // consumer. It would be nicer to have a real configurable line
2408   // table emitter.
2409   if (LineTable.Prologue.Version != 2 ||
2410       LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2411       LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2412       LineTable.Prologue.OpcodeBase != 13)
2413     reportWarning("line table paramters mismatch. Cannot emit.");
2414   else
2415     Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2416                                    LineTable.Prologue.MinInstLength, NewRows,
2417                                    Unit.getOrigUnit().getAddressByteSize());
2418 }
2419
2420 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2421   Streamer->emitPubNamesForUnit(Unit);
2422   Streamer->emitPubTypesForUnit(Unit);
2423 }
2424
2425 bool DwarfLinker::link(const DebugMap &Map) {
2426
2427   if (Map.begin() == Map.end()) {
2428     errs() << "Empty debug map.\n";
2429     return false;
2430   }
2431
2432   if (!createStreamer(Map.getTriple(), OutputFilename))
2433     return false;
2434
2435   // Size of the DIEs (and headers) generated for the linked output.
2436   uint64_t OutputDebugInfoSize = 0;
2437   // A unique ID that identifies each compile unit.
2438   unsigned UnitID = 0;
2439   for (const auto &Obj : Map.objects()) {
2440     CurrentDebugObject = Obj.get();
2441
2442     if (Options.Verbose)
2443       outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2444     auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2445     if (std::error_code EC = ErrOrObj.getError()) {
2446       reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
2447       continue;
2448     }
2449
2450     // Look for relocations that correspond to debug map entries.
2451     if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
2452       if (Options.Verbose)
2453         outs() << "No valid relocations found. Skipping.\n";
2454       continue;
2455     }
2456
2457     // Setup access to the debug info.
2458     DWARFContextInMemory DwarfContext(*ErrOrObj);
2459     startDebugObject(DwarfContext, *Obj);
2460
2461     // In a first phase, just read in the debug info and store the DIE
2462     // parent links that we will use during the next phase.
2463     for (const auto &CU : DwarfContext.compile_units()) {
2464       auto *CUDie = CU->getUnitDIE(false);
2465       if (Options.Verbose) {
2466         outs() << "Input compilation unit:";
2467         CUDie->dump(outs(), CU.get(), 0);
2468       }
2469       Units.emplace_back(*CU, UnitID++);
2470       gatherDIEParents(CUDie, 0, Units.back());
2471     }
2472
2473     // Then mark all the DIEs that need to be present in the linked
2474     // output and collect some information about them. Note that this
2475     // loop can not be merged with the previous one becaue cross-cu
2476     // references require the ParentIdx to be setup for every CU in
2477     // the object file before calling this.
2478     for (auto &CurrentUnit : Units)
2479       lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
2480                         CurrentUnit, 0);
2481
2482     // The calls to applyValidRelocs inside cloneDIE will walk the
2483     // reloc array again (in the same way findValidRelocsInDebugInfo()
2484     // did). We need to reset the NextValidReloc index to the beginning.
2485     NextValidReloc = 0;
2486
2487     // Construct the output DIE tree by cloning the DIEs we chose to
2488     // keep above. If there are no valid relocs, then there's nothing
2489     // to clone/emit.
2490     if (!ValidRelocs.empty())
2491       for (auto &CurrentUnit : Units) {
2492         const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
2493         CurrentUnit.setStartOffset(OutputDebugInfoSize);
2494         DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2495                                   11 /* Unit Header size */);
2496         CurrentUnit.setOutputUnitDIE(OutputDIE);
2497         OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
2498         if (Options.NoOutput)
2499           continue;
2500         // FIXME: for compatibility with the classic dsymutil, we emit
2501         // an empty line table for the unit, even if the unit doesn't
2502         // actually exist in the DIE tree.
2503         patchLineTableForUnit(CurrentUnit, DwarfContext);
2504         if (!OutputDIE)
2505           continue;
2506         patchRangesForUnit(CurrentUnit, DwarfContext);
2507         Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
2508         emitAcceleratorEntriesForUnit(CurrentUnit);
2509       }
2510
2511     // Emit all the compile unit's debug information.
2512     if (!ValidRelocs.empty() && !Options.NoOutput)
2513       for (auto &CurrentUnit : Units) {
2514         generateUnitRanges(CurrentUnit);
2515         CurrentUnit.fixupForwardReferences();
2516         Streamer->emitCompileUnitHeader(CurrentUnit);
2517         if (!CurrentUnit.getOutputUnitDIE())
2518           continue;
2519         Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2520       }
2521
2522     // Clean-up before starting working on the next object.
2523     endDebugObject();
2524   }
2525
2526   // Emit everything that's global.
2527   if (!Options.NoOutput) {
2528     Streamer->emitAbbrevs(Abbreviations);
2529     Streamer->emitStrings(StringPool);
2530   }
2531
2532   return Options.NoOutput ? true : Streamer->finish();
2533 }
2534 }
2535
2536 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2537                const LinkOptions &Options) {
2538   DwarfLinker Linker(OutputFilename, Options);
2539   return Linker.link(DM);
2540 }
2541 }
2542 }