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