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