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