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