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