This removes the eating of the error in Archive::Child::getSize() when the characters
[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 "MachOUtils.h"
14 #include "NonRelocatableStringpool.h"
15 #include "llvm/ADT/IntervalMap.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/DIE.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
23 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
24 #include "llvm/MC/MCAsmBackend.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCCodeEmitter.h"
28 #include "llvm/MC/MCDwarf.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/Object/MachO.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/LEB128.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include <string>
41 #include <tuple>
42
43 namespace llvm {
44 namespace dsymutil {
45
46 namespace {
47
48 template <typename KeyT, typename ValT>
49 using HalfOpenIntervalMap =
50     IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
51                 IntervalMapHalfOpenInfo<KeyT>>;
52
53 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
54
55 // FIXME: Delete this structure.
56 struct PatchLocation {
57   DIE::value_iterator I;
58
59   PatchLocation() = default;
60   PatchLocation(DIE::value_iterator I) : I(I) {}
61
62   void set(uint64_t New) const {
63     assert(I);
64     const auto &Old = *I;
65     assert(Old.getType() == DIEValue::isInteger);
66     *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
67   }
68
69   uint64_t get() const {
70     assert(I);
71     return I->getDIEInteger().getValue();
72   }
73 };
74
75 class CompileUnit;
76 struct DeclMapInfo;
77
78 /// A DeclContext is a named program scope that is used for ODR
79 /// uniquing of types.
80 /// The set of DeclContext for the ODR-subject parts of a Dwarf link
81 /// is expanded (and uniqued) with each new object file processed. We
82 /// need to determine the context of each DIE in an linked object file
83 /// to see if the corresponding type has already been emitted.
84 ///
85 /// The contexts are conceptually organised as a tree (eg. a function
86 /// scope is contained in a namespace scope that contains other
87 /// scopes), but storing/accessing them in an actual tree is too
88 /// inefficient: we need to be able to very quickly query a context
89 /// for a given child context by name. Storing a StringMap in each
90 /// DeclContext would be too space inefficient.
91 /// The solution here is to give each DeclContext a link to its parent
92 /// (this allows to walk up the tree), but to query the existance of a
93 /// specific DeclContext using a separate DenseMap keyed on the hash
94 /// of the fully qualified name of the context.
95 class DeclContext {
96   unsigned QualifiedNameHash;
97   uint32_t Line;
98   uint32_t ByteSize;
99   uint16_t Tag;
100   StringRef Name;
101   StringRef File;
102   const DeclContext &Parent;
103   const DWARFDebugInfoEntryMinimal *LastSeenDIE;
104   uint32_t LastSeenCompileUnitID;
105   uint32_t CanonicalDIEOffset;
106
107   friend DeclMapInfo;
108
109 public:
110   typedef DenseSet<DeclContext *, DeclMapInfo> Map;
111
112   DeclContext()
113       : QualifiedNameHash(0), Line(0), ByteSize(0),
114         Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
115         LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
116
117   DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
118               StringRef Name, StringRef File, const DeclContext &Parent,
119               const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
120               unsigned CUId = 0)
121       : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
122         Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
123         LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
124
125   uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
126
127   bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
128
129   uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
130   void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
131
132   uint16_t getTag() const { return Tag; }
133   StringRef getName() const { return Name; }
134 };
135
136 /// Info type for the DenseMap storing the DeclContext pointers.
137 struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
138   using DenseMapInfo<DeclContext *>::getEmptyKey;
139   using DenseMapInfo<DeclContext *>::getTombstoneKey;
140
141   static unsigned getHashValue(const DeclContext *Ctxt) {
142     return Ctxt->QualifiedNameHash;
143   }
144
145   static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
146     if (RHS == getEmptyKey() || RHS == getTombstoneKey())
147       return RHS == LHS;
148     return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
149            LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
150            LHS->Name.data() == RHS->Name.data() &&
151            LHS->File.data() == RHS->File.data() &&
152            LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
153   }
154 };
155
156 /// This class gives a tree-like API to the DenseMap that stores the
157 /// DeclContext objects. It also holds the BumpPtrAllocator where
158 /// these objects will be allocated.
159 class DeclContextTree {
160   BumpPtrAllocator Allocator;
161   DeclContext Root;
162   DeclContext::Map Contexts;
163
164 public:
165   /// Get the child of \a Context described by \a DIE in \a Unit. The
166   /// required strings will be interned in \a StringPool.
167   /// \returns The child DeclContext along with one bit that is set if
168   /// this context is invalid.
169   /// An invalid context means it shouldn't be considered for uniquing, but its
170   /// not returning null, because some children of that context might be
171   /// uniquing candidates.  FIXME: The invalid bit along the return value is to
172   /// emulate some dsymutil-classic functionality.
173   PointerIntPair<DeclContext *, 1>
174   getChildDeclContext(DeclContext &Context,
175                       const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
176                       NonRelocatableStringpool &StringPool, bool InClangModule);
177
178   DeclContext &getRoot() { return Root; }
179 };
180
181 /// \brief Stores all information relating to a compile unit, be it in
182 /// its original instance in the object file to its brand new cloned
183 /// and linked DIE tree.
184 class CompileUnit {
185 public:
186   /// \brief Information gathered about a DIE in the object file.
187   struct DIEInfo {
188     int64_t AddrAdjust; ///< Address offset to apply to the described entity.
189     DeclContext *Ctxt;  ///< ODR Declaration context.
190     DIE *Clone;         ///< Cloned version of that DIE.
191     uint32_t ParentIdx; ///< The index of this DIE's parent.
192     bool Keep : 1;      ///< Is the DIE part of the linked output?
193     bool InDebugMap : 1;///< Was this DIE's entity found in the map?
194     bool Prune : 1;     ///< Is this a pure forward declaration we can strip?
195   };
196
197   CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR,
198               StringRef ClangModuleName)
199       : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
200         Ranges(RangeAlloc), ClangModuleName(ClangModuleName) {
201     Info.resize(OrigUnit.getNumDIEs());
202
203     const auto *CUDie = OrigUnit.getUnitDIE(false);
204     unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
205         &OrigUnit, dwarf::DW_AT_language, 0);
206     HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
207                            Lang == dwarf::DW_LANG_C_plus_plus_03 ||
208                            Lang == dwarf::DW_LANG_C_plus_plus_11 ||
209                            Lang == dwarf::DW_LANG_C_plus_plus_14 ||
210                            Lang == dwarf::DW_LANG_ObjC_plus_plus);
211   }
212
213   CompileUnit(CompileUnit &&RHS)
214       : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
215         CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
216         NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
217     // The CompileUnit container has been 'reserve()'d with the right
218     // size. We cannot move the IntervalMap anyway.
219     llvm_unreachable("CompileUnits should not be moved.");
220   }
221
222   DWARFUnit &getOrigUnit() const { return OrigUnit; }
223
224   unsigned getUniqueID() const { return ID; }
225
226   DIE *getOutputUnitDIE() const { return CUDie; }
227   void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
228
229   bool hasODR() const { return HasODR; }
230   bool isClangModule() const { return !ClangModuleName.empty(); }
231   const std::string &getClangModuleName() const { return ClangModuleName; }
232
233   DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
234   const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
235
236   uint64_t getStartOffset() const { return StartOffset; }
237   uint64_t getNextUnitOffset() const { return NextUnitOffset; }
238   void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
239
240   uint64_t getLowPc() const { return LowPc; }
241   uint64_t getHighPc() const { return HighPc; }
242
243   Optional<PatchLocation> getUnitRangesAttribute() const {
244     return UnitRangeAttribute;
245   }
246   const FunctionIntervals &getFunctionRanges() const { return Ranges; }
247   const std::vector<PatchLocation> &getRangesAttributes() const {
248     return RangeAttributes;
249   }
250
251   const std::vector<std::pair<PatchLocation, int64_t>> &
252   getLocationAttributes() const {
253     return LocationAttributes;
254   }
255
256   void setHasInterestingContent() { HasInterestingContent = true; }
257   bool hasInterestingContent() { return HasInterestingContent; }
258
259   /// Mark every DIE in this unit as kept. This function also
260   /// marks variables as InDebugMap so that they appear in the
261   /// reconstructed accelerator tables.
262   void markEverythingAsKept();
263
264   /// \brief Compute the end offset for this unit. Must be
265   /// called after the CU's DIEs have been cloned.
266   /// \returns the next unit offset (which is also the current
267   /// debug_info section size).
268   uint64_t computeNextUnitOffset();
269
270   /// \brief Keep track of a forward reference to DIE \p Die in \p
271   /// RefUnit by \p Attr. The attribute should be fixed up later to
272   /// point to the absolute offset of \p Die in the debug_info section
273   /// or to the canonical offset of \p Ctxt if it is non-null.
274   void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
275                             DeclContext *Ctxt, PatchLocation Attr);
276
277   /// \brief Apply all fixups recored by noteForwardReference().
278   void fixupForwardReferences();
279
280   /// \brief Add a function range [\p LowPC, \p HighPC) that is
281   /// relocatad by applying offset \p PCOffset.
282   void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
283
284   /// \brief Keep track of a DW_AT_range attribute that we will need to
285   /// patch up later.
286   void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
287
288   /// \brief Keep track of a location attribute pointing to a location
289   /// list in the debug_loc section.
290   void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
291
292   /// \brief Add a name accelerator entry for \p Die with \p Name
293   /// which is stored in the string table at \p Offset.
294   void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
295                           bool SkipPubnamesSection = false);
296
297   /// \brief Add a type accelerator entry for \p Die with \p Name
298   /// which is stored in the string table at \p Offset.
299   void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
300
301   struct AccelInfo {
302     StringRef Name;      ///< Name of the entry.
303     const DIE *Die;      ///< DIE this entry describes.
304     uint32_t NameOffset; ///< Offset of Name in the string pool.
305     bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
306
307     AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
308               bool SkipPubSection = false)
309         : Name(Name), Die(Die), NameOffset(NameOffset),
310           SkipPubSection(SkipPubSection) {}
311   };
312
313   const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
314   const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
315
316   /// Get the full path for file \a FileNum in the line table
317   const char *getResolvedPath(unsigned FileNum) {
318     if (FileNum >= ResolvedPaths.size())
319       return nullptr;
320     return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
321                                          : nullptr;
322   }
323
324   /// Set the fully resolved path for the line-table's file \a FileNum
325   /// to \a Path.
326   void setResolvedPath(unsigned FileNum, const std::string &Path) {
327     if (ResolvedPaths.size() <= FileNum)
328       ResolvedPaths.resize(FileNum + 1);
329     ResolvedPaths[FileNum] = Path;
330   }
331
332 private:
333   DWARFUnit &OrigUnit;
334   unsigned ID;
335   std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
336   DIE *CUDie;                ///< Root of the linked DIE tree.
337
338   uint64_t StartOffset;
339   uint64_t NextUnitOffset;
340
341   uint64_t LowPc;
342   uint64_t HighPc;
343
344   /// \brief A list of attributes to fixup with the absolute offset of
345   /// a DIE in the debug_info section.
346   ///
347   /// The offsets for the attributes in this array couldn't be set while
348   /// cloning because for cross-cu forward refences the target DIE's
349   /// offset isn't known you emit the reference attribute.
350   std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
351                          PatchLocation>> ForwardDIEReferences;
352
353   FunctionIntervals::Allocator RangeAlloc;
354   /// \brief The ranges in that interval map are the PC ranges for
355   /// functions in this unit, associated with the PC offset to apply
356   /// to the addresses to get the linked address.
357   FunctionIntervals Ranges;
358
359   /// \brief DW_AT_ranges attributes to patch after we have gathered
360   /// all the unit's function addresses.
361   /// @{
362   std::vector<PatchLocation> RangeAttributes;
363   Optional<PatchLocation> UnitRangeAttribute;
364   /// @}
365
366   /// \brief Location attributes that need to be transfered from th
367   /// original debug_loc section to the liked one. They are stored
368   /// along with the PC offset that is to be applied to their
369   /// function's address.
370   std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
371
372   /// \brief Accelerator entries for the unit, both for the pub*
373   /// sections and the apple* ones.
374   /// @{
375   std::vector<AccelInfo> Pubnames;
376   std::vector<AccelInfo> Pubtypes;
377   /// @}
378
379   /// Cached resolved paths from the line table.
380   std::vector<std::string> ResolvedPaths;
381
382   /// Is this unit subject to the ODR rule?
383   bool HasODR;
384   /// Did a DIE actually contain a valid reloc?
385   bool HasInterestingContent;
386   /// If this is a Clang module, this holds the module's name.
387   std::string ClangModuleName;
388 };
389
390 void CompileUnit::markEverythingAsKept() {
391   for (auto &I : Info)
392     // Mark everything that wasn't explicity marked for pruning.
393     I.Keep = !I.Prune;
394 }
395
396 uint64_t CompileUnit::computeNextUnitOffset() {
397   NextUnitOffset = StartOffset + 11 /* Header size */;
398   // The root DIE might be null, meaning that the Unit had nothing to
399   // contribute to the linked output. In that case, we will emit the
400   // unit header without any actual DIE.
401   if (CUDie)
402     NextUnitOffset += CUDie->getSize();
403   return NextUnitOffset;
404 }
405
406 /// \brief Keep track of a forward cross-cu reference from this unit
407 /// to \p Die that lives in \p RefUnit.
408 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
409                                        DeclContext *Ctxt, PatchLocation Attr) {
410   ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
411 }
412
413 /// \brief Apply all fixups recorded by noteForwardReference().
414 void CompileUnit::fixupForwardReferences() {
415   for (const auto &Ref : ForwardDIEReferences) {
416     DIE *RefDie;
417     const CompileUnit *RefUnit;
418     PatchLocation Attr;
419     DeclContext *Ctxt;
420     std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
421     if (Ctxt && Ctxt->getCanonicalDIEOffset())
422       Attr.set(Ctxt->getCanonicalDIEOffset());
423     else
424       Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
425   }
426 }
427
428 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
429                                    int64_t PcOffset) {
430   Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
431   this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
432   this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
433 }
434
435 void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
436   if (Die.getTag() != dwarf::DW_TAG_compile_unit)
437     RangeAttributes.push_back(Attr);
438   else
439     UnitRangeAttribute = Attr;
440 }
441
442 void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
443   LocationAttributes.emplace_back(Attr, PcOffset);
444 }
445
446 /// \brief Add a name accelerator entry for \p Die with \p Name
447 /// which is stored in the string table at \p Offset.
448 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
449                                      uint32_t Offset, bool SkipPubSection) {
450   Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
451 }
452
453 /// \brief Add a type accelerator entry for \p Die with \p Name
454 /// which is stored in the string table at \p Offset.
455 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
456                                      uint32_t Offset) {
457   Pubtypes.emplace_back(Name, Die, Offset, false);
458 }
459
460 /// \brief The Dwarf streaming logic
461 ///
462 /// All interactions with the MC layer that is used to build the debug
463 /// information binary representation are handled in this class.
464 class DwarfStreamer {
465   /// \defgroup MCObjects MC layer objects constructed by the streamer
466   /// @{
467   std::unique_ptr<MCRegisterInfo> MRI;
468   std::unique_ptr<MCAsmInfo> MAI;
469   std::unique_ptr<MCObjectFileInfo> MOFI;
470   std::unique_ptr<MCContext> MC;
471   MCAsmBackend *MAB; // Owned by MCStreamer
472   std::unique_ptr<MCInstrInfo> MII;
473   std::unique_ptr<MCSubtargetInfo> MSTI;
474   MCCodeEmitter *MCE; // Owned by MCStreamer
475   MCStreamer *MS;     // Owned by AsmPrinter
476   std::unique_ptr<TargetMachine> TM;
477   std::unique_ptr<AsmPrinter> Asm;
478   /// @}
479
480   /// \brief the file we stream the linked Dwarf to.
481   std::unique_ptr<raw_fd_ostream> OutFile;
482
483   uint32_t RangesSectionSize;
484   uint32_t LocSectionSize;
485   uint32_t LineSectionSize;
486   uint32_t FrameSectionSize;
487
488   /// \brief Emit the pubnames or pubtypes section contribution for \p
489   /// Unit into \p Sec. The data is provided in \p Names.
490   void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
491                              const CompileUnit &Unit,
492                              const std::vector<CompileUnit::AccelInfo> &Names);
493
494 public:
495   /// \brief Actually create the streamer and the ouptut file.
496   ///
497   /// This could be done directly in the constructor, but it feels
498   /// more natural to handle errors through return value.
499   bool init(Triple TheTriple, StringRef OutputFilename);
500
501   /// \brief Dump the file to the disk.
502   bool finish(const DebugMap &);
503
504   AsmPrinter &getAsmPrinter() const { return *Asm; }
505
506   /// \brief Set the current output section to debug_info and change
507   /// the MC Dwarf version to \p DwarfVersion.
508   void switchToDebugInfoSection(unsigned DwarfVersion);
509
510   /// \brief Emit the compilation unit header for \p Unit in the
511   /// debug_info section.
512   ///
513   /// As a side effect, this also switches the current Dwarf version
514   /// of the MC layer to the one of U.getOrigUnit().
515   void emitCompileUnitHeader(CompileUnit &Unit);
516
517   /// \brief Recursively emit the DIE tree rooted at \p Die.
518   void emitDIE(DIE &Die);
519
520   /// \brief Emit the abbreviation table \p Abbrevs to the
521   /// debug_abbrev section.
522   void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
523
524   /// \brief Emit the string table described by \p Pool.
525   void emitStrings(const NonRelocatableStringpool &Pool);
526
527   /// \brief Emit debug_ranges for \p FuncRange by translating the
528   /// original \p Entries.
529   void emitRangesEntries(
530       int64_t UnitPcOffset, uint64_t OrigLowPc,
531       FunctionIntervals::const_iterator FuncRange,
532       const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
533       unsigned AddressSize);
534
535   /// \brief Emit debug_aranges entries for \p Unit and if \p
536   /// DoRangesSection is true, also emit the debug_ranges entries for
537   /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
538   void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
539
540   uint32_t getRangesSectionSize() const { return RangesSectionSize; }
541
542   /// \brief Emit the debug_loc contribution for \p Unit by copying
543   /// the entries from \p Dwarf and offseting them. Update the
544   /// location attributes to point to the new entries.
545   void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
546
547   /// \brief Emit the line table described in \p Rows into the
548   /// debug_line section.
549   void emitLineTableForUnit(MCDwarfLineTableParams Params,
550                             StringRef PrologueBytes, unsigned MinInstLength,
551                             std::vector<DWARFDebugLine::Row> &Rows,
552                             unsigned AdddressSize);
553
554   uint32_t getLineSectionSize() const { return LineSectionSize; }
555
556   /// \brief Emit the .debug_pubnames contribution for \p Unit.
557   void emitPubNamesForUnit(const CompileUnit &Unit);
558
559   /// \brief Emit the .debug_pubtypes contribution for \p Unit.
560   void emitPubTypesForUnit(const CompileUnit &Unit);
561
562   /// \brief Emit a CIE.
563   void emitCIE(StringRef CIEBytes);
564
565   /// \brief Emit an FDE with data \p Bytes.
566   void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
567                StringRef Bytes);
568
569   uint32_t getFrameSectionSize() const { return FrameSectionSize; }
570 };
571
572 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
573   std::string ErrorStr;
574   std::string TripleName;
575   StringRef Context = "dwarf streamer init";
576
577   // Get the target.
578   const Target *TheTarget =
579       TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
580   if (!TheTarget)
581     return error(ErrorStr, Context);
582   TripleName = TheTriple.getTriple();
583
584   // Create all the MC Objects.
585   MRI.reset(TheTarget->createMCRegInfo(TripleName));
586   if (!MRI)
587     return error(Twine("no register info for target ") + TripleName, Context);
588
589   MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
590   if (!MAI)
591     return error("no asm info for target " + TripleName, Context);
592
593   MOFI.reset(new MCObjectFileInfo);
594   MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
595   MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
596                              *MC);
597
598   MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
599   if (!MAB)
600     return error("no asm backend for target " + TripleName, Context);
601
602   MII.reset(TheTarget->createMCInstrInfo());
603   if (!MII)
604     return error("no instr info info for target " + TripleName, Context);
605
606   MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
607   if (!MSTI)
608     return error("no subtarget info for target " + TripleName, Context);
609
610   MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
611   if (!MCE)
612     return error("no code emitter for target " + TripleName, Context);
613
614   // Create the output file.
615   std::error_code EC;
616   OutFile =
617       llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
618   if (EC)
619     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
620
621   MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
622                                          *MSTI, false,
623                                          /*DWARFMustBeAtTheEnd*/ false);
624   if (!MS)
625     return error("no object streamer for target " + TripleName, Context);
626
627   // Finally create the AsmPrinter we'll use to emit the DIEs.
628   TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
629   if (!TM)
630     return error("no target machine for target " + TripleName, Context);
631
632   Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
633   if (!Asm)
634     return error("no asm printer for target " + TripleName, Context);
635
636   RangesSectionSize = 0;
637   LocSectionSize = 0;
638   LineSectionSize = 0;
639   FrameSectionSize = 0;
640
641   return true;
642 }
643
644 bool DwarfStreamer::finish(const DebugMap &DM) {
645   if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
646     return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
647
648   MS->Finish();
649   return true;
650 }
651
652 /// \brief Set the current output section to debug_info and change
653 /// the MC Dwarf version to \p DwarfVersion.
654 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
655   MS->SwitchSection(MOFI->getDwarfInfoSection());
656   MC->setDwarfVersion(DwarfVersion);
657 }
658
659 /// \brief Emit the compilation unit header for \p Unit in the
660 /// debug_info section.
661 ///
662 /// A Dwarf scetion header is encoded as:
663 ///  uint32_t   Unit length (omiting this field)
664 ///  uint16_t   Version
665 ///  uint32_t   Abbreviation table offset
666 ///  uint8_t    Address size
667 ///
668 /// Leading to a total of 11 bytes.
669 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
670   unsigned Version = Unit.getOrigUnit().getVersion();
671   switchToDebugInfoSection(Version);
672
673   // Emit size of content not including length itself. The size has
674   // already been computed in CompileUnit::computeOffsets(). Substract
675   // 4 to that size to account for the length field.
676   Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
677   Asm->EmitInt16(Version);
678   // We share one abbreviations table across all units so it's always at the
679   // start of the section.
680   Asm->EmitInt32(0);
681   Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
682 }
683
684 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
685 /// for the linked Dwarf file.
686 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
687   MS->SwitchSection(MOFI->getDwarfAbbrevSection());
688   Asm->emitDwarfAbbrevs(Abbrevs);
689 }
690
691 /// \brief Recursively emit the DIE tree rooted at \p Die.
692 void DwarfStreamer::emitDIE(DIE &Die) {
693   MS->SwitchSection(MOFI->getDwarfInfoSection());
694   Asm->emitDwarfDIE(Die);
695 }
696
697 /// \brief Emit the debug_str section stored in \p Pool.
698 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
699   Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
700   for (auto *Entry = Pool.getFirstEntry(); Entry;
701        Entry = Pool.getNextEntry(Entry))
702     Asm->OutStreamer->EmitBytes(
703         StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
704 }
705
706 /// \brief Emit the debug_range section contents for \p FuncRange by
707 /// translating the original \p Entries. The debug_range section
708 /// format is totally trivial, consisting just of pairs of address
709 /// sized addresses describing the ranges.
710 void DwarfStreamer::emitRangesEntries(
711     int64_t UnitPcOffset, uint64_t OrigLowPc,
712     FunctionIntervals::const_iterator FuncRange,
713     const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
714     unsigned AddressSize) {
715   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
716
717   // Offset each range by the right amount.
718   int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
719   for (const auto &Range : Entries) {
720     if (Range.isBaseAddressSelectionEntry(AddressSize)) {
721       warn("unsupported base address selection operation",
722            "emitting debug_ranges");
723       break;
724     }
725     // Do not emit empty ranges.
726     if (Range.StartAddress == Range.EndAddress)
727       continue;
728
729     // All range entries should lie in the function range.
730     if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
731           Range.EndAddress + OrigLowPc <= FuncRange.stop()))
732       warn("inconsistent range data.", "emitting debug_ranges");
733     MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
734     MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
735     RangesSectionSize += 2 * AddressSize;
736   }
737
738   // Add the terminator entry.
739   MS->EmitIntValue(0, AddressSize);
740   MS->EmitIntValue(0, AddressSize);
741   RangesSectionSize += 2 * AddressSize;
742 }
743
744 /// \brief Emit the debug_aranges contribution of a unit and
745 /// if \p DoDebugRanges is true the debug_range contents for a
746 /// compile_unit level DW_AT_ranges attribute (Which are basically the
747 /// same thing with a different base address).
748 /// Just aggregate all the ranges gathered inside that unit.
749 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
750                                           bool DoDebugRanges) {
751   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
752   // Gather the ranges in a vector, so that we can simplify them. The
753   // IntervalMap will have coalesced the non-linked ranges, but here
754   // we want to coalesce the linked addresses.
755   std::vector<std::pair<uint64_t, uint64_t>> Ranges;
756   const auto &FunctionRanges = Unit.getFunctionRanges();
757   for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
758        Range != End; ++Range)
759     Ranges.push_back(std::make_pair(Range.start() + Range.value(),
760                                     Range.stop() + Range.value()));
761
762   // The object addresses where sorted, but again, the linked
763   // addresses might end up in a different order.
764   std::sort(Ranges.begin(), Ranges.end());
765
766   if (!Ranges.empty()) {
767     MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
768
769     MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
770     MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
771
772     unsigned HeaderSize =
773         sizeof(int32_t) + // Size of contents (w/o this field
774         sizeof(int16_t) + // DWARF ARange version number
775         sizeof(int32_t) + // Offset of CU in the .debug_info section
776         sizeof(int8_t) +  // Pointer Size (in bytes)
777         sizeof(int8_t);   // Segment Size (in bytes)
778
779     unsigned TupleSize = AddressSize * 2;
780     unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
781
782     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
783     Asm->OutStreamer->EmitLabel(BeginLabel);
784     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
785     Asm->EmitInt32(Unit.getStartOffset());     // Corresponding unit's offset
786     Asm->EmitInt8(AddressSize);                // Address size
787     Asm->EmitInt8(0);                          // Segment size
788
789     Asm->OutStreamer->EmitFill(Padding, 0x0);
790
791     for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
792          ++Range) {
793       uint64_t RangeStart = Range->first;
794       MS->EmitIntValue(RangeStart, AddressSize);
795       while ((Range + 1) != End && Range->second == (Range + 1)->first)
796         ++Range;
797       MS->EmitIntValue(Range->second - RangeStart, AddressSize);
798     }
799
800     // Emit terminator
801     Asm->OutStreamer->EmitIntValue(0, AddressSize);
802     Asm->OutStreamer->EmitIntValue(0, AddressSize);
803     Asm->OutStreamer->EmitLabel(EndLabel);
804   }
805
806   if (!DoDebugRanges)
807     return;
808
809   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
810   // Offset each range by the right amount.
811   int64_t PcOffset = -Unit.getLowPc();
812   // Emit coalesced ranges.
813   for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
814     MS->EmitIntValue(Range->first + PcOffset, AddressSize);
815     while (Range + 1 != End && Range->second == (Range + 1)->first)
816       ++Range;
817     MS->EmitIntValue(Range->second + PcOffset, AddressSize);
818     RangesSectionSize += 2 * AddressSize;
819   }
820
821   // Add the terminator entry.
822   MS->EmitIntValue(0, AddressSize);
823   MS->EmitIntValue(0, AddressSize);
824   RangesSectionSize += 2 * AddressSize;
825 }
826
827 /// \brief Emit location lists for \p Unit and update attribtues to
828 /// point to the new entries.
829 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
830                                          DWARFContext &Dwarf) {
831   const auto &Attributes = Unit.getLocationAttributes();
832
833   if (Attributes.empty())
834     return;
835
836   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
837
838   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
839   const DWARFSection &InputSec = Dwarf.getLocSection();
840   DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
841   DWARFUnit &OrigUnit = Unit.getOrigUnit();
842   const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
843   int64_t UnitPcOffset = 0;
844   uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
845       &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
846   if (OrigLowPc != -1ULL)
847     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
848
849   for (const auto &Attr : Attributes) {
850     uint32_t Offset = Attr.first.get();
851     Attr.first.set(LocSectionSize);
852     // This is the quantity to add to the old location address to get
853     // the correct address for the new one.
854     int64_t LocPcOffset = Attr.second + UnitPcOffset;
855     while (Data.isValidOffset(Offset)) {
856       uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
857       uint64_t High = Data.getUnsigned(&Offset, AddressSize);
858       LocSectionSize += 2 * AddressSize;
859       if (Low == 0 && High == 0) {
860         Asm->OutStreamer->EmitIntValue(0, AddressSize);
861         Asm->OutStreamer->EmitIntValue(0, AddressSize);
862         break;
863       }
864       Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
865       Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
866       uint64_t Length = Data.getU16(&Offset);
867       Asm->OutStreamer->EmitIntValue(Length, 2);
868       // Just copy the bytes over.
869       Asm->OutStreamer->EmitBytes(
870           StringRef(InputSec.Data.substr(Offset, Length)));
871       Offset += Length;
872       LocSectionSize += Length + 2;
873     }
874   }
875 }
876
877 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
878                                          StringRef PrologueBytes,
879                                          unsigned MinInstLength,
880                                          std::vector<DWARFDebugLine::Row> &Rows,
881                                          unsigned PointerSize) {
882   // Switch to the section where the table will be emitted into.
883   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
884   MCSymbol *LineStartSym = MC->createTempSymbol();
885   MCSymbol *LineEndSym = MC->createTempSymbol();
886
887   // The first 4 bytes is the total length of the information for this
888   // compilation unit (not including these 4 bytes for the length).
889   Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
890   Asm->OutStreamer->EmitLabel(LineStartSym);
891   // Copy Prologue.
892   MS->EmitBytes(PrologueBytes);
893   LineSectionSize += PrologueBytes.size() + 4;
894
895   SmallString<128> EncodingBuffer;
896   raw_svector_ostream EncodingOS(EncodingBuffer);
897
898   if (Rows.empty()) {
899     // We only have the dummy entry, dsymutil emits an entry with a 0
900     // address in that case.
901     MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
902     MS->EmitBytes(EncodingOS.str());
903     LineSectionSize += EncodingBuffer.size();
904     MS->EmitLabel(LineEndSym);
905     return;
906   }
907
908   // Line table state machine fields
909   unsigned FileNum = 1;
910   unsigned LastLine = 1;
911   unsigned Column = 0;
912   unsigned IsStatement = 1;
913   unsigned Isa = 0;
914   uint64_t Address = -1ULL;
915
916   unsigned RowsSinceLastSequence = 0;
917
918   for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
919     auto &Row = Rows[Idx];
920
921     int64_t AddressDelta;
922     if (Address == -1ULL) {
923       MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
924       MS->EmitULEB128IntValue(PointerSize + 1);
925       MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
926       MS->EmitIntValue(Row.Address, PointerSize);
927       LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
928       AddressDelta = 0;
929     } else {
930       AddressDelta = (Row.Address - Address) / MinInstLength;
931     }
932
933     // FIXME: code copied and transfromed from
934     // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
935     // this code, but the current compatibility requirement with
936     // classic dsymutil makes it hard. Revisit that once this
937     // requirement is dropped.
938
939     if (FileNum != Row.File) {
940       FileNum = Row.File;
941       MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
942       MS->EmitULEB128IntValue(FileNum);
943       LineSectionSize += 1 + getULEB128Size(FileNum);
944     }
945     if (Column != Row.Column) {
946       Column = Row.Column;
947       MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
948       MS->EmitULEB128IntValue(Column);
949       LineSectionSize += 1 + getULEB128Size(Column);
950     }
951
952     // FIXME: We should handle the discriminator here, but dsymutil
953     // doesn' consider it, thus ignore it for now.
954
955     if (Isa != Row.Isa) {
956       Isa = Row.Isa;
957       MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
958       MS->EmitULEB128IntValue(Isa);
959       LineSectionSize += 1 + getULEB128Size(Isa);
960     }
961     if (IsStatement != Row.IsStmt) {
962       IsStatement = Row.IsStmt;
963       MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
964       LineSectionSize += 1;
965     }
966     if (Row.BasicBlock) {
967       MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
968       LineSectionSize += 1;
969     }
970
971     if (Row.PrologueEnd) {
972       MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
973       LineSectionSize += 1;
974     }
975
976     if (Row.EpilogueBegin) {
977       MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
978       LineSectionSize += 1;
979     }
980
981     int64_t LineDelta = int64_t(Row.Line) - LastLine;
982     if (!Row.EndSequence) {
983       MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
984       MS->EmitBytes(EncodingOS.str());
985       LineSectionSize += EncodingBuffer.size();
986       EncodingBuffer.resize(0);
987       Address = Row.Address;
988       LastLine = Row.Line;
989       RowsSinceLastSequence++;
990     } else {
991       if (LineDelta) {
992         MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
993         MS->EmitSLEB128IntValue(LineDelta);
994         LineSectionSize += 1 + getSLEB128Size(LineDelta);
995       }
996       if (AddressDelta) {
997         MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
998         MS->EmitULEB128IntValue(AddressDelta);
999         LineSectionSize += 1 + getULEB128Size(AddressDelta);
1000       }
1001       MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
1002       MS->EmitBytes(EncodingOS.str());
1003       LineSectionSize += EncodingBuffer.size();
1004       EncodingBuffer.resize(0);
1005       Address = -1ULL;
1006       LastLine = FileNum = IsStatement = 1;
1007       RowsSinceLastSequence = Column = Isa = 0;
1008     }
1009   }
1010
1011   if (RowsSinceLastSequence) {
1012     MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
1013     MS->EmitBytes(EncodingOS.str());
1014     LineSectionSize += EncodingBuffer.size();
1015     EncodingBuffer.resize(0);
1016   }
1017
1018   MS->EmitLabel(LineEndSym);
1019 }
1020
1021 /// \brief Emit the pubnames or pubtypes section contribution for \p
1022 /// Unit into \p Sec. The data is provided in \p Names.
1023 void DwarfStreamer::emitPubSectionForUnit(
1024     MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
1025     const std::vector<CompileUnit::AccelInfo> &Names) {
1026   if (Names.empty())
1027     return;
1028
1029   // Start the dwarf pubnames section.
1030   Asm->OutStreamer->SwitchSection(Sec);
1031   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1032   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
1033
1034   bool HeaderEmitted = false;
1035   // Emit the pubnames for this compilation unit.
1036   for (const auto &Name : Names) {
1037     if (Name.SkipPubSection)
1038       continue;
1039
1040     if (!HeaderEmitted) {
1041       // Emit the header.
1042       Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
1043       Asm->OutStreamer->EmitLabel(BeginLabel);
1044       Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
1045       Asm->EmitInt32(Unit.getStartOffset());      // Unit offset
1046       Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1047       HeaderEmitted = true;
1048     }
1049     Asm->EmitInt32(Name.Die->getOffset());
1050     Asm->OutStreamer->EmitBytes(
1051         StringRef(Name.Name.data(), Name.Name.size() + 1));
1052   }
1053
1054   if (!HeaderEmitted)
1055     return;
1056   Asm->EmitInt32(0); // End marker.
1057   Asm->OutStreamer->EmitLabel(EndLabel);
1058 }
1059
1060 /// \brief Emit .debug_pubnames for \p Unit.
1061 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1062   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1063                         "names", Unit, Unit.getPubnames());
1064 }
1065
1066 /// \brief Emit .debug_pubtypes for \p Unit.
1067 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1068   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1069                         "types", Unit, Unit.getPubtypes());
1070 }
1071
1072 /// \brief Emit a CIE into the debug_frame section.
1073 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1074   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1075
1076   MS->EmitBytes(CIEBytes);
1077   FrameSectionSize += CIEBytes.size();
1078 }
1079
1080 /// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1081 /// contains the FDE data without the length, CIE offset and address
1082 /// which will be replaced with the paramter values.
1083 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1084                             uint32_t Address, StringRef FDEBytes) {
1085   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1086
1087   MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1088   MS->EmitIntValue(CIEOffset, 4);
1089   MS->EmitIntValue(Address, AddrSize);
1090   MS->EmitBytes(FDEBytes);
1091   FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1092 }
1093
1094 /// \brief The core of the Dwarf linking logic.
1095 ///
1096 /// The link of the dwarf information from the object files will be
1097 /// driven by the selection of 'root DIEs', which are DIEs that
1098 /// describe variables or functions that are present in the linked
1099 /// binary (and thus have entries in the debug map). All the debug
1100 /// information that will be linked (the DIEs, but also the line
1101 /// tables, ranges, ...) is derived from that set of root DIEs.
1102 ///
1103 /// The root DIEs are identified because they contain relocations that
1104 /// correspond to a debug map entry at specific places (the low_pc for
1105 /// a function, the location for a variable). These relocations are
1106 /// called ValidRelocs in the DwarfLinker and are gathered as a very
1107 /// first step when we start processing a DebugMapObject.
1108 class DwarfLinker {
1109 public:
1110   DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1111       : OutputFilename(OutputFilename), Options(Options),
1112         BinHolder(Options.Verbose), LastCIEOffset(0) {}
1113
1114   ~DwarfLinker() {
1115     for (auto *Abbrev : Abbreviations)
1116       delete Abbrev;
1117   }
1118
1119   /// \brief Link the contents of the DebugMap.
1120   bool link(const DebugMap &);
1121
1122   void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1123                      const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1124
1125 private:
1126   /// \brief Called at the start of a debug object link.
1127   void startDebugObject(DWARFContext &, DebugMapObject &);
1128
1129   /// \brief Called at the end of a debug object link.
1130   void endDebugObject();
1131
1132   /// Keeps track of relocations.
1133   class RelocationManager {
1134     struct ValidReloc {
1135       uint32_t Offset;
1136       uint32_t Size;
1137       uint64_t Addend;
1138       const DebugMapObject::DebugMapEntry *Mapping;
1139
1140       ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1141                  const DebugMapObject::DebugMapEntry *Mapping)
1142           : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1143
1144       bool operator<(const ValidReloc &RHS) const {
1145         return Offset < RHS.Offset;
1146       }
1147     };
1148
1149     DwarfLinker &Linker;
1150
1151     /// \brief The valid relocations for the current DebugMapObject.
1152     /// This vector is sorted by relocation offset.
1153     std::vector<ValidReloc> ValidRelocs;
1154
1155     /// \brief Index into ValidRelocs of the next relocation to
1156     /// consider. As we walk the DIEs in acsending file offset and as
1157     /// ValidRelocs is sorted by file offset, keeping this index
1158     /// uptodate is all we have to do to have a cheap lookup during the
1159     /// root DIE selection and during DIE cloning.
1160     unsigned NextValidReloc;
1161
1162   public:
1163     RelocationManager(DwarfLinker &Linker)
1164         : Linker(Linker), NextValidReloc(0) {}
1165
1166     bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1167     /// \brief Reset the NextValidReloc counter.
1168     void resetValidRelocs() { NextValidReloc = 0; }
1169
1170     /// \defgroup FindValidRelocations Translate debug map into a list
1171     /// of relevant relocations
1172     ///
1173     /// @{
1174     bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1175                                     const DebugMapObject &DMO);
1176
1177     bool findValidRelocs(const object::SectionRef &Section,
1178                          const object::ObjectFile &Obj,
1179                          const DebugMapObject &DMO);
1180
1181     void findValidRelocsMachO(const object::SectionRef &Section,
1182                               const object::MachOObjectFile &Obj,
1183                               const DebugMapObject &DMO);
1184     /// @}
1185
1186     bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1187                             CompileUnit::DIEInfo &Info);
1188
1189     bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1190                           bool isLittleEndian);
1191   };
1192
1193   /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1194   ///
1195   /// @{
1196   /// \brief Recursively walk the \p DIE tree and look for DIEs to
1197   /// keep. Store that information in \p CU's DIEInfo.
1198   void lookForDIEsToKeep(RelocationManager &RelocMgr,
1199                          const DWARFDebugInfoEntryMinimal &DIE,
1200                          const DebugMapObject &DMO, CompileUnit &CU,
1201                          unsigned Flags);
1202
1203   /// If this compile unit is really a skeleton CU that points to a
1204   /// clang module, register it in ClangModules and return true.
1205   ///
1206   /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1207   /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1208   /// hash.
1209   bool registerModuleReference(const DWARFDebugInfoEntryMinimal &CUDie,
1210                                const DWARFUnit &Unit, DebugMap &ModuleMap,
1211                                unsigned Indent = 0);
1212
1213   /// Recursively add the debug info in this clang module .pcm
1214   /// file (and all the modules imported by it in a bottom-up fashion)
1215   /// to Units.
1216   void loadClangModule(StringRef Filename, StringRef ModulePath,
1217                        StringRef ModuleName, uint64_t DwoId,
1218                        DebugMap &ModuleMap, unsigned Indent = 0);
1219
1220   /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1221   enum TravesalFlags {
1222     TF_Keep = 1 << 0,            ///< Mark the traversed DIEs as kept.
1223     TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1224     TF_DependencyWalk = 1 << 2,  ///< Walking the dependencies of a kept DIE.
1225     TF_ParentWalk = 1 << 3,      ///< Walking up the parents of a kept DIE.
1226     TF_ODR = 1 << 4,             ///< Use the ODR whhile keeping dependants.
1227     TF_SkipPC = 1 << 5,          ///< Skip all location attributes.
1228   };
1229
1230   /// \brief Mark the passed DIE as well as all the ones it depends on
1231   /// as kept.
1232   void keepDIEAndDependencies(RelocationManager &RelocMgr,
1233                                const DWARFDebugInfoEntryMinimal &DIE,
1234                                CompileUnit::DIEInfo &MyInfo,
1235                                const DebugMapObject &DMO, CompileUnit &CU,
1236                                bool UseODR);
1237
1238   unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1239                          const DWARFDebugInfoEntryMinimal &DIE,
1240                          CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1241                          unsigned Flags);
1242
1243   unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1244                                  const DWARFDebugInfoEntryMinimal &DIE,
1245                                  CompileUnit &Unit,
1246                                  CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1247
1248   unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1249                                    const DWARFDebugInfoEntryMinimal &DIE,
1250                                    CompileUnit &Unit,
1251                                    CompileUnit::DIEInfo &MyInfo,
1252                                    unsigned Flags);
1253
1254   bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1255                           CompileUnit::DIEInfo &Info);
1256   /// @}
1257
1258   /// \defgroup Linking Methods used to link the debug information
1259   ///
1260   /// @{
1261
1262   class DIECloner {
1263     DwarfLinker &Linker;
1264     RelocationManager &RelocMgr;
1265     /// Allocator used for all the DIEValue objects.
1266     BumpPtrAllocator &DIEAlloc;
1267     MutableArrayRef<CompileUnit> CompileUnits;
1268     LinkOptions Options;
1269
1270   public:
1271     DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1272               BumpPtrAllocator &DIEAlloc,
1273               MutableArrayRef<CompileUnit> CompileUnits, LinkOptions &Options)
1274         : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1275           CompileUnits(CompileUnits), Options(Options) {}
1276
1277     /// Recursively clone \p InputDIE into an tree of DIE objects
1278     /// where useless (as decided by lookForDIEsToKeep()) bits have been
1279     /// stripped out and addresses have been rewritten according to the
1280     /// debug map.
1281     ///
1282     /// \param OutOffset is the offset the cloned DIE in the output
1283     /// compile unit.
1284     /// \param PCOffset (while cloning a function scope) is the offset
1285     /// applied to the entry point of the function to get the linked address.
1286     ///
1287     /// \returns the root of the cloned tree or null if nothing was selected.
1288     DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
1289                   int64_t PCOffset, uint32_t OutOffset, unsigned Flags);
1290
1291     /// Construct the output DIE tree by cloning the DIEs we
1292     /// chose to keep above. If there are no valid relocs, then there's
1293     /// nothing to clone/emit.
1294     void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
1295
1296   private:
1297     typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1298
1299     /// Information gathered and exchanged between the various
1300     /// clone*Attributes helpers about the attributes of a particular DIE.
1301     struct AttributesInfo {
1302       const char *Name, *MangledName;         ///< Names.
1303       uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1304
1305       uint64_t OrigLowPc;  ///< Value of AT_low_pc in the input DIE
1306       uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1307       int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1308
1309       bool HasLowPc;      ///< Does the DIE have a low_pc attribute?
1310       bool IsDeclaration; ///< Is this DIE only a declaration?
1311
1312       AttributesInfo()
1313           : Name(nullptr), MangledName(nullptr), NameOffset(0),
1314             MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1315             PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1316     };
1317
1318     /// Helper for cloneDIE.
1319     unsigned cloneAttribute(DIE &Die,
1320                             const DWARFDebugInfoEntryMinimal &InputDIE,
1321                             CompileUnit &U, const DWARFFormValue &Val,
1322                             const AttributeSpec AttrSpec, unsigned AttrSize,
1323                             AttributesInfo &AttrInfo);
1324
1325     /// Clone a string attribute described by \p AttrSpec and add
1326     /// it to \p Die.
1327     /// \returns the size of the new attribute.
1328     unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1329                                   const DWARFFormValue &Val,
1330                                   const DWARFUnit &U);
1331
1332     /// Clone an attribute referencing another DIE and add
1333     /// it to \p Die.
1334     /// \returns the size of the new attribute.
1335     unsigned
1336     cloneDieReferenceAttribute(DIE &Die,
1337                                const DWARFDebugInfoEntryMinimal &InputDIE,
1338                                AttributeSpec AttrSpec, unsigned AttrSize,
1339                                const DWARFFormValue &Val, CompileUnit &Unit);
1340
1341     /// Clone an attribute referencing another DIE and add
1342     /// it to \p Die.
1343     /// \returns the size of the new attribute.
1344     unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1345                                  const DWARFFormValue &Val, unsigned AttrSize);
1346
1347     /// Clone an attribute referencing another DIE and add
1348     /// it to \p Die.
1349     /// \returns the size of the new attribute.
1350     unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1351                                    const DWARFFormValue &Val,
1352                                    const CompileUnit &Unit,
1353                                    AttributesInfo &Info);
1354
1355     /// Clone a scalar attribute  and add it to \p Die.
1356     /// \returns the size of the new attribute.
1357     unsigned cloneScalarAttribute(DIE &Die,
1358                                   const DWARFDebugInfoEntryMinimal &InputDIE,
1359                                   CompileUnit &U, AttributeSpec AttrSpec,
1360                                   const DWARFFormValue &Val, unsigned AttrSize,
1361                                   AttributesInfo &Info);
1362
1363     /// Get the potential name and mangled name for the entity
1364     /// described by \p Die and store them in \Info if they are not
1365     /// already there.
1366     /// \returns is a name was found.
1367     bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1368                      AttributesInfo &Info);
1369
1370     /// Create a copy of abbreviation Abbrev.
1371     void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
1372   };
1373
1374   /// \brief Assign an abbreviation number to \p Abbrev
1375   void AssignAbbrev(DIEAbbrev &Abbrev);
1376
1377   /// \brief FoldingSet that uniques the abbreviations.
1378   FoldingSet<DIEAbbrev> AbbreviationsSet;
1379   /// \brief Storage for the unique Abbreviations.
1380   /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1381   /// be changed to a vecot of unique_ptrs.
1382   std::vector<DIEAbbrev *> Abbreviations;
1383
1384   /// \brief Compute and emit debug_ranges section for \p Unit, and
1385   /// patch the attributes referencing it.
1386   void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1387
1388   /// \brief Generate and emit the DW_AT_ranges attribute for a
1389   /// compile_unit if it had one.
1390   void generateUnitRanges(CompileUnit &Unit) const;
1391
1392   /// \brief Extract the line tables fromt he original dwarf, extract
1393   /// the relevant parts according to the linked function ranges and
1394   /// emit the result in the debug_line section.
1395   void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1396
1397   /// \brief Emit the accelerator entries for \p Unit.
1398   void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1399
1400   /// \brief Patch the frame info for an object file and emit it.
1401   void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1402                                unsigned AddressSize);
1403
1404   /// \brief DIELoc objects that need to be destructed (but not freed!).
1405   std::vector<DIELoc *> DIELocs;
1406   /// \brief DIEBlock objects that need to be destructed (but not freed!).
1407   std::vector<DIEBlock *> DIEBlocks;
1408   /// \brief Allocator used for all the DIEValue objects.
1409   BumpPtrAllocator DIEAlloc;
1410   /// @}
1411
1412   /// ODR Contexts for that link.
1413   DeclContextTree ODRContexts;
1414
1415   /// \defgroup Helpers Various helper methods.
1416   ///
1417   /// @{
1418   bool createStreamer(Triple TheTriple, StringRef OutputFilename);
1419
1420   /// \brief Attempt to load a debug object from disk.
1421   ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1422                                                  DebugMapObject &Obj,
1423                                                  const DebugMap &Map);
1424   /// @}
1425
1426   std::string OutputFilename;
1427   LinkOptions Options;
1428   BinaryHolder BinHolder;
1429   std::unique_ptr<DwarfStreamer> Streamer;
1430   uint64_t OutputDebugInfoSize;
1431   unsigned UnitID; ///< A unique ID that identifies each compile unit.
1432
1433   /// The units of the current debug map object.
1434   std::vector<CompileUnit> Units;
1435
1436   /// The debug map object curently under consideration.
1437   DebugMapObject *CurrentDebugObject;
1438
1439   /// \brief The Dwarf string pool
1440   NonRelocatableStringpool StringPool;
1441
1442   /// \brief This map is keyed by the entry PC of functions in that
1443   /// debug object and the associated value is a pair storing the
1444   /// corresponding end PC and the offset to apply to get the linked
1445   /// address.
1446   ///
1447   /// See startDebugObject() for a more complete description of its use.
1448   std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1449
1450   /// \brief The CIEs that have been emitted in the output
1451   /// section. The actual CIE data serves a the key to this StringMap,
1452   /// this takes care of comparing the semantics of CIEs defined in
1453   /// different object files.
1454   StringMap<uint32_t> EmittedCIEs;
1455
1456   /// Offset of the last CIE that has been emitted in the output
1457   /// debug_frame section.
1458   uint32_t LastCIEOffset;
1459
1460   /// Mapping the PCM filename to the DwoId.
1461   StringMap<uint64_t> ClangModules;
1462 };
1463
1464 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1465 /// CompileUnit object instead.
1466 static CompileUnit *getUnitForOffset(MutableArrayRef<CompileUnit> Units,
1467                                      unsigned Offset) {
1468   auto CU =
1469       std::upper_bound(Units.begin(), Units.end(), Offset,
1470                        [](uint32_t LHS, const CompileUnit &RHS) {
1471                          return LHS < RHS.getOrigUnit().getNextUnitOffset();
1472                        });
1473   return CU != Units.end() ? &*CU : nullptr;
1474 }
1475
1476 /// Resolve the DIE attribute reference that has been
1477 /// extracted in \p RefValue. The resulting DIE migh be in another
1478 /// CompileUnit which is stored into \p ReferencedCU.
1479 /// \returns null if resolving fails for any reason.
1480 static const DWARFDebugInfoEntryMinimal *resolveDIEReference(
1481     const DwarfLinker &Linker, MutableArrayRef<CompileUnit> Units,
1482     const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1483     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1484   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1485   uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1486
1487   if ((RefCU = getUnitForOffset(Units, RefOffset)))
1488     if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1489       return RefDie;
1490
1491   Linker.reportWarning("could not find referenced DIE", &Unit, &DIE);
1492   return nullptr;
1493 }
1494
1495 /// \returns whether the passed \a Attr type might contain a DIE
1496 /// reference suitable for ODR uniquing.
1497 static bool isODRAttribute(uint16_t Attr) {
1498   switch (Attr) {
1499   default:
1500     return false;
1501   case dwarf::DW_AT_type:
1502   case dwarf::DW_AT_containing_type:
1503   case dwarf::DW_AT_specification:
1504   case dwarf::DW_AT_abstract_origin:
1505   case dwarf::DW_AT_import:
1506     return true;
1507   }
1508   llvm_unreachable("Improper attribute.");
1509 }
1510
1511 /// Set the last DIE/CU a context was seen in and, possibly invalidate
1512 /// the context if it is ambiguous.
1513 ///
1514 /// In the current implementation, we don't handle overloaded
1515 /// functions well, because the argument types are not taken into
1516 /// account when computing the DeclContext tree.
1517 ///
1518 /// Some of this is mitigated byt using mangled names that do contain
1519 /// the arguments types, but sometimes (eg. with function templates)
1520 /// we don't have that. In that case, just do not unique anything that
1521 /// refers to the contexts we are not able to distinguish.
1522 ///
1523 /// If a context that is not a namespace appears twice in the same CU,
1524 /// we know it is ambiguous. Make it invalid.
1525 bool DeclContext::setLastSeenDIE(CompileUnit &U,
1526                                  const DWARFDebugInfoEntryMinimal *Die) {
1527   if (LastSeenCompileUnitID == U.getUniqueID()) {
1528     DWARFUnit &OrigUnit = U.getOrigUnit();
1529     uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1530     U.getInfo(FirstIdx).Ctxt = nullptr;
1531     return false;
1532   }
1533
1534   LastSeenCompileUnitID = U.getUniqueID();
1535   LastSeenDIE = Die;
1536   return true;
1537 }
1538
1539 PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1540     DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1541     NonRelocatableStringpool &StringPool, bool InClangModule) {
1542   unsigned Tag = DIE->getTag();
1543
1544   // FIXME: dsymutil-classic compat: We should bail out here if we
1545   // have a specification or an abstract_origin. We will get the
1546   // parent context wrong here.
1547
1548   switch (Tag) {
1549   default:
1550     // By default stop gathering child contexts.
1551     return PointerIntPair<DeclContext *, 1>(nullptr);
1552   case dwarf::DW_TAG_module:
1553     break;
1554   case dwarf::DW_TAG_compile_unit:
1555     return PointerIntPair<DeclContext *, 1>(&Context);
1556   case dwarf::DW_TAG_subprogram:
1557     // Do not unique anything inside CU local functions.
1558     if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1559          Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1560         !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1561                                                   dwarf::DW_AT_external, 0))
1562       return PointerIntPair<DeclContext *, 1>(nullptr);
1563   // Fallthrough
1564   case dwarf::DW_TAG_member:
1565   case dwarf::DW_TAG_namespace:
1566   case dwarf::DW_TAG_structure_type:
1567   case dwarf::DW_TAG_class_type:
1568   case dwarf::DW_TAG_union_type:
1569   case dwarf::DW_TAG_enumeration_type:
1570   case dwarf::DW_TAG_typedef:
1571     // Artificial things might be ambiguous, because they might be
1572     // created on demand. For example implicitely defined constructors
1573     // are ambiguous because of the way we identify contexts, and they
1574     // won't be generated everytime everywhere.
1575     if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1576                                                  dwarf::DW_AT_artificial, 0))
1577       return PointerIntPair<DeclContext *, 1>(nullptr);
1578     break;
1579   }
1580
1581   const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1582   const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1583   StringRef NameRef;
1584   StringRef ShortNameRef;
1585   StringRef FileRef;
1586
1587   if (Name)
1588     NameRef = StringPool.internString(Name);
1589   else if (Tag == dwarf::DW_TAG_namespace)
1590     // FIXME: For dsymutil-classic compatibility. I think uniquing
1591     // within anonymous namespaces is wrong. There is no ODR guarantee
1592     // there.
1593     NameRef = StringPool.internString("(anonymous namespace)");
1594
1595   if (ShortName && ShortName != Name)
1596     ShortNameRef = StringPool.internString(ShortName);
1597   else
1598     ShortNameRef = NameRef;
1599
1600   if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1601       Tag != dwarf::DW_TAG_union_type &&
1602       Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1603     return PointerIntPair<DeclContext *, 1>(nullptr);
1604
1605   std::string File;
1606   unsigned Line = 0;
1607   unsigned ByteSize = UINT32_MAX;
1608
1609   if (!InClangModule) {
1610     // Gather some discriminating data about the DeclContext we will be
1611     // creating: File, line number and byte size. This shouldn't be
1612     // necessary, because the ODR is just about names, but given that we
1613     // do some approximations with overloaded functions and anonymous
1614     // namespaces, use these additional data points to make the process
1615     // safer.  This is disabled for clang modules, because forward
1616     // declarations of module-defined types do not have a file and line.
1617     ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1618         &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1619     if (Tag != dwarf::DW_TAG_namespace || !Name) {
1620       if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1621               &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1622         if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1623                 &U.getOrigUnit())) {
1624           // FIXME: dsymutil-classic compatibility. I'd rather not
1625           // unique anything in anonymous namespaces, but if we do, then
1626           // verify that the file and line correspond.
1627           if (!Name && Tag == dwarf::DW_TAG_namespace)
1628             FileNum = 1;
1629
1630           // FIXME: Passing U.getOrigUnit().getCompilationDir()
1631           // instead of "" would allow more uniquing, but for now, do
1632           // it this way to match dsymutil-classic.
1633           if (LT->getFileNameByIndex(
1634                   FileNum, "",
1635                   DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1636                   File)) {
1637             Line = DIE->getAttributeValueAsUnsignedConstant(
1638                 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1639 #ifdef HAVE_REALPATH
1640             // Cache the resolved paths, because calling realpath is expansive.
1641             if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1642               File = ResolvedPath;
1643             } else {
1644               char RealPath[PATH_MAX + 1];
1645               RealPath[PATH_MAX] = 0;
1646               if (::realpath(File.c_str(), RealPath))
1647                 File = RealPath;
1648               U.setResolvedPath(FileNum, File);
1649             }
1650 #endif
1651             FileRef = StringPool.internString(File);
1652           }
1653         }
1654       }
1655     }
1656   }
1657
1658   if (!Line && NameRef.empty())
1659     return PointerIntPair<DeclContext *, 1>(nullptr);
1660
1661   // We hash NameRef, which is the mangled name, in order to get most
1662   // overloaded functions resolve correctly.
1663   //
1664   // Strictly speaking, hashing the Tag is only necessary for a
1665   // DW_TAG_module, to prevent uniquing of a module and a namespace
1666   // with the same name.
1667   //
1668   // FIXME: dsymutil-classic won't unique the same type presented
1669   // once as a struct and once as a class. Using the Tag in the fully
1670   // qualified name hash to get the same effect.
1671   unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1672
1673   // FIXME: dsymutil-classic compatibility: when we don't have a name,
1674   // use the filename.
1675   if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1676     Hash = hash_combine(Hash, FileRef);
1677
1678   // Now look if this context already exists.
1679   DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1680   auto ContextIter = Contexts.find(&Key);
1681
1682   if (ContextIter == Contexts.end()) {
1683     // The context wasn't found.
1684     bool Inserted;
1685     DeclContext *NewContext =
1686         new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1687                                     Context, DIE, U.getUniqueID());
1688     std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1689     assert(Inserted && "Failed to insert DeclContext");
1690     (void)Inserted;
1691   } else if (Tag != dwarf::DW_TAG_namespace &&
1692              !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1693     // The context was found, but it is ambiguous with another context
1694     // in the same file. Mark it invalid.
1695     return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1696   }
1697
1698   assert(ContextIter != Contexts.end());
1699   // FIXME: dsymutil-classic compatibility. Union types aren't
1700   // uniques, but their children might be.
1701   if ((Tag == dwarf::DW_TAG_subprogram &&
1702        Context.getTag() != dwarf::DW_TAG_structure_type &&
1703        Context.getTag() != dwarf::DW_TAG_class_type) ||
1704       (Tag == dwarf::DW_TAG_union_type))
1705     return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1706
1707   return PointerIntPair<DeclContext *, 1>(*ContextIter);
1708 }
1709
1710 bool DwarfLinker::DIECloner::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1711                                          DWARFUnit &U, AttributesInfo &Info) {
1712   // FIXME: a bit wasteful as the first getName might return the
1713   // short name.
1714   if (!Info.MangledName &&
1715       (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1716     Info.MangledNameOffset =
1717         Linker.StringPool.getStringOffset(Info.MangledName);
1718
1719   if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1720     Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
1721
1722   return Info.Name || Info.MangledName;
1723 }
1724
1725 /// \brief Report a warning to the user, optionaly including
1726 /// information about a specific \p DIE related to the warning.
1727 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1728                                 const DWARFDebugInfoEntryMinimal *DIE) const {
1729   StringRef Context = "<debug map>";
1730   if (CurrentDebugObject)
1731     Context = CurrentDebugObject->getObjectFilename();
1732   warn(Warning, Context);
1733
1734   if (!Options.Verbose || !DIE)
1735     return;
1736
1737   errs() << "    in DIE:\n";
1738   DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1739             6 /* Indent */);
1740 }
1741
1742 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1743   if (Options.NoOutput)
1744     return true;
1745
1746   Streamer = llvm::make_unique<DwarfStreamer>();
1747   return Streamer->init(TheTriple, OutputFilename);
1748 }
1749
1750 /// Recursive helper to build the global DeclContext information and
1751 /// gather the child->parent relationships in the original compile unit.
1752 ///
1753 /// \return true when this DIE and all of its children are only
1754 /// forward declarations to types defined in external clang modules
1755 /// (i.e., forward declarations that are children of a DW_TAG_module).
1756 static bool analyzeContextInfo(const DWARFDebugInfoEntryMinimal *DIE,
1757                                unsigned ParentIdx, CompileUnit &CU,
1758                                DeclContext *CurrentDeclContext,
1759                                NonRelocatableStringpool &StringPool,
1760                                DeclContextTree &Contexts,
1761                                bool InImportedModule = false) {
1762   unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1763   CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1764
1765   // Clang imposes an ODR on modules(!) regardless of the language:
1766   //  "The module-id should consist of only a single identifier,
1767   //   which provides the name of the module being defined. Each
1768   //   module shall have a single definition."
1769   //
1770   // This does not extend to the types inside the modules:
1771   //  "[I]n C, this implies that if two structs are defined in
1772   //   different submodules with the same name, those two types are
1773   //   distinct types (but may be compatible types if their
1774   //   definitions match)."
1775   //
1776   // We treat non-C++ modules like namespaces for this reason.
1777   if (DIE->getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
1778       DIE->getAttributeValueAsString(&CU.getOrigUnit(), dwarf::DW_AT_name,
1779                                      "") != CU.getClangModuleName()) {
1780     InImportedModule = true;
1781   }
1782
1783   Info.ParentIdx = ParentIdx;
1784   bool InClangModule = CU.isClangModule() || InImportedModule;
1785   if (CU.hasODR() || InClangModule) {
1786     if (CurrentDeclContext) {
1787       auto PtrInvalidPair = Contexts.getChildDeclContext(
1788           *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
1789       CurrentDeclContext = PtrInvalidPair.getPointer();
1790       Info.Ctxt =
1791           PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1792     } else
1793       Info.Ctxt = CurrentDeclContext = nullptr;
1794   }
1795
1796   Info.Prune = InImportedModule;
1797   if (DIE->hasChildren())
1798     for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1799          Child = Child->getSibling())
1800       Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
1801                                        StringPool, Contexts, InImportedModule);
1802
1803   // Prune this DIE if it is either a forward declaration inside a
1804   // DW_TAG_module or a DW_TAG_module that contains nothing but
1805   // forward declarations.
1806   Info.Prune &= (DIE->getTag() == dwarf::DW_TAG_module) ||
1807                 DIE->getAttributeValueAsUnsignedConstant(
1808                     &CU.getOrigUnit(), dwarf::DW_AT_declaration, 0);
1809
1810   // Don't prune it if there is no definition for the DIE.
1811   Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
1812
1813   return Info.Prune;
1814 }
1815
1816 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1817   switch (Tag) {
1818   default:
1819     return false;
1820   case dwarf::DW_TAG_subprogram:
1821   case dwarf::DW_TAG_lexical_block:
1822   case dwarf::DW_TAG_subroutine_type:
1823   case dwarf::DW_TAG_structure_type:
1824   case dwarf::DW_TAG_class_type:
1825   case dwarf::DW_TAG_union_type:
1826     return true;
1827   }
1828   llvm_unreachable("Invalid Tag");
1829 }
1830
1831 static unsigned getRefAddrSize(const DWARFUnit &U) {
1832   if (U.getVersion() == 2)
1833     return U.getAddressByteSize();
1834   return 4;
1835 }
1836
1837 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1838   Units.reserve(Dwarf.getNumCompileUnits());
1839   // Iterate over the debug map entries and put all the ones that are
1840   // functions (because they have a size) into the Ranges map. This
1841   // map is very similar to the FunctionRanges that are stored in each
1842   // unit, with 2 notable differences:
1843   //  - obviously this one is global, while the other ones are per-unit.
1844   //  - this one contains not only the functions described in the DIE
1845   // tree, but also the ones that are only in the debug map.
1846   // The latter information is required to reproduce dsymutil's logic
1847   // while linking line tables. The cases where this information
1848   // matters look like bugs that need to be investigated, but for now
1849   // we need to reproduce dsymutil's behavior.
1850   // FIXME: Once we understood exactly if that information is needed,
1851   // maybe totally remove this (or try to use it to do a real
1852   // -gline-tables-only on Darwin.
1853   for (const auto &Entry : Obj.symbols()) {
1854     const auto &Mapping = Entry.getValue();
1855     if (Mapping.Size)
1856       Ranges[Mapping.ObjectAddress] = std::make_pair(
1857           Mapping.ObjectAddress + Mapping.Size,
1858           int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1859   }
1860 }
1861
1862 void DwarfLinker::endDebugObject() {
1863   Units.clear();
1864   Ranges.clear();
1865
1866   for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1867     (*I)->~DIEBlock();
1868   for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1869     (*I)->~DIELoc();
1870
1871   DIEBlocks.clear();
1872   DIELocs.clear();
1873   DIEAlloc.Reset();
1874 }
1875
1876 /// \brief Iterate over the relocations of the given \p Section and
1877 /// store the ones that correspond to debug map entries into the
1878 /// ValidRelocs array.
1879 void DwarfLinker::RelocationManager::
1880 findValidRelocsMachO(const object::SectionRef &Section,
1881                      const object::MachOObjectFile &Obj,
1882                      const DebugMapObject &DMO) {
1883   StringRef Contents;
1884   Section.getContents(Contents);
1885   DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1886
1887   for (const object::RelocationRef &Reloc : Section.relocations()) {
1888     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1889     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1890     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1891     uint64_t Offset64 = Reloc.getOffset();
1892     if ((RelocSize != 4 && RelocSize != 8)) {
1893       Linker.reportWarning(" unsupported relocation in debug_info section.");
1894       continue;
1895     }
1896     uint32_t Offset = Offset64;
1897     // Mach-o uses REL relocations, the addend is at the relocation offset.
1898     uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1899
1900     auto Sym = Reloc.getSymbol();
1901     if (Sym != Obj.symbol_end()) {
1902       ErrorOr<StringRef> SymbolName = Sym->getName();
1903       if (!SymbolName) {
1904         Linker.reportWarning("error getting relocation symbol name.");
1905         continue;
1906       }
1907       if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
1908         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1909     } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1910       // Do not store the addend. The addend was the address of the
1911       // symbol in the object file, the address in the binary that is
1912       // stored in the debug map doesn't need to be offseted.
1913       ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1914     }
1915   }
1916 }
1917
1918 /// \brief Dispatch the valid relocation finding logic to the
1919 /// appropriate handler depending on the object file format.
1920 bool DwarfLinker::RelocationManager::findValidRelocs(
1921     const object::SectionRef &Section, const object::ObjectFile &Obj,
1922     const DebugMapObject &DMO) {
1923   // Dispatch to the right handler depending on the file type.
1924   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1925     findValidRelocsMachO(Section, *MachOObj, DMO);
1926   else
1927     Linker.reportWarning(Twine("unsupported object file type: ") +
1928                          Obj.getFileName());
1929
1930   if (ValidRelocs.empty())
1931     return false;
1932
1933   // Sort the relocations by offset. We will walk the DIEs linearly in
1934   // the file, this allows us to just keep an index in the relocation
1935   // array that we advance during our walk, rather than resorting to
1936   // some associative container. See DwarfLinker::NextValidReloc.
1937   std::sort(ValidRelocs.begin(), ValidRelocs.end());
1938   return true;
1939 }
1940
1941 /// \brief Look for relocations in the debug_info section that match
1942 /// entries in the debug map. These relocations will drive the Dwarf
1943 /// link by indicating which DIEs refer to symbols present in the
1944 /// linked binary.
1945 /// \returns wether there are any valid relocations in the debug info.
1946 bool DwarfLinker::RelocationManager::
1947 findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1948                            const DebugMapObject &DMO) {
1949   // Find the debug_info section.
1950   for (const object::SectionRef &Section : Obj.sections()) {
1951     StringRef SectionName;
1952     Section.getName(SectionName);
1953     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1954     if (SectionName != "debug_info")
1955       continue;
1956     return findValidRelocs(Section, Obj, DMO);
1957   }
1958   return false;
1959 }
1960
1961 /// \brief Checks that there is a relocation against an actual debug
1962 /// map entry between \p StartOffset and \p NextOffset.
1963 ///
1964 /// This function must be called with offsets in strictly ascending
1965 /// order because it never looks back at relocations it already 'went past'.
1966 /// \returns true and sets Info.InDebugMap if it is the case.
1967 bool DwarfLinker::RelocationManager::
1968 hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1969                    CompileUnit::DIEInfo &Info) {
1970   assert(NextValidReloc == 0 ||
1971          StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1972   if (NextValidReloc >= ValidRelocs.size())
1973     return false;
1974
1975   uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1976
1977   // We might need to skip some relocs that we didn't consider. For
1978   // example the high_pc of a discarded DIE might contain a reloc that
1979   // is in the list because it actually corresponds to the start of a
1980   // function that is in the debug map.
1981   while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1982     RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1983
1984   if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1985     return false;
1986
1987   const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1988   const auto &Mapping = ValidReloc.Mapping->getValue();
1989   if (Linker.Options.Verbose)
1990     outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1991            << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1992                             uint64_t(Mapping.ObjectAddress),
1993                             uint64_t(Mapping.BinaryAddress));
1994
1995   Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1996                     Mapping.ObjectAddress;
1997   Info.InDebugMap = true;
1998   return true;
1999 }
2000
2001 /// \brief Get the starting and ending (exclusive) offset for the
2002 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
2003 /// supposed to point to the position of the first attribute described
2004 /// by \p Abbrev.
2005 /// \return [StartOffset, EndOffset) as a pair.
2006 static std::pair<uint32_t, uint32_t>
2007 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
2008                     unsigned Offset, const DWARFUnit &Unit) {
2009   DataExtractor Data = Unit.getDebugInfoExtractor();
2010
2011   for (unsigned i = 0; i < Idx; ++i)
2012     DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
2013
2014   uint32_t End = Offset;
2015   DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
2016
2017   return std::make_pair(Offset, End);
2018 }
2019
2020 /// \brief Check if a variable describing DIE should be kept.
2021 /// \returns updated TraversalFlags.
2022 unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
2023                                             const DWARFDebugInfoEntryMinimal &DIE,
2024                                             CompileUnit &Unit,
2025                                             CompileUnit::DIEInfo &MyInfo,
2026                                             unsigned Flags) {
2027   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2028
2029   // Global variables with constant value can always be kept.
2030   if (!(Flags & TF_InFunctionScope) &&
2031       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
2032     MyInfo.InDebugMap = true;
2033     return Flags | TF_Keep;
2034   }
2035
2036   uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
2037   if (LocationIdx == -1U)
2038     return Flags;
2039
2040   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2041   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2042   uint32_t LocationOffset, LocationEndOffset;
2043   std::tie(LocationOffset, LocationEndOffset) =
2044       getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
2045
2046   // See if there is a relocation to a valid debug map entry inside
2047   // this variable's location. The order is important here. We want to
2048   // always check in the variable has a valid relocation, so that the
2049   // DIEInfo is filled. However, we don't want a static variable in a
2050   // function to force us to keep the enclosing function.
2051   if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
2052       (Flags & TF_InFunctionScope))
2053     return Flags;
2054
2055   if (Options.Verbose)
2056     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2057
2058   return Flags | TF_Keep;
2059 }
2060
2061 /// \brief Check if a function describing DIE should be kept.
2062 /// \returns updated TraversalFlags.
2063 unsigned DwarfLinker::shouldKeepSubprogramDIE(
2064     RelocationManager &RelocMgr,
2065     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2066     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2067   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2068
2069   Flags |= TF_InFunctionScope;
2070
2071   uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2072   if (LowPcIdx == -1U)
2073     return Flags;
2074
2075   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2076   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2077   uint32_t LowPcOffset, LowPcEndOffset;
2078   std::tie(LowPcOffset, LowPcEndOffset) =
2079       getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2080
2081   uint64_t LowPc =
2082       DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2083   assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2084   if (LowPc == -1ULL ||
2085       !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
2086     return Flags;
2087
2088   if (Options.Verbose)
2089     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2090
2091   Flags |= TF_Keep;
2092
2093   DWARFFormValue HighPcValue;
2094   if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2095     reportWarning("Function without high_pc. Range will be discarded.\n",
2096                   &OrigUnit, &DIE);
2097     return Flags;
2098   }
2099
2100   uint64_t HighPc;
2101   if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2102     HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2103   } else {
2104     assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2105     HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2106   }
2107
2108   // Replace the debug map range with a more accurate one.
2109   Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
2110   Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2111   return Flags;
2112 }
2113
2114 /// \brief Check if a DIE should be kept.
2115 /// \returns updated TraversalFlags.
2116 unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2117                                     const DWARFDebugInfoEntryMinimal &DIE,
2118                                     CompileUnit &Unit,
2119                                     CompileUnit::DIEInfo &MyInfo,
2120                                     unsigned Flags) {
2121   switch (DIE.getTag()) {
2122   case dwarf::DW_TAG_constant:
2123   case dwarf::DW_TAG_variable:
2124     return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
2125   case dwarf::DW_TAG_subprogram:
2126     return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
2127   case dwarf::DW_TAG_module:
2128   case dwarf::DW_TAG_imported_module:
2129   case dwarf::DW_TAG_imported_declaration:
2130   case dwarf::DW_TAG_imported_unit:
2131     // We always want to keep these.
2132     return Flags | TF_Keep;
2133   }
2134
2135   return Flags;
2136 }
2137
2138 /// \brief Mark the passed DIE as well as all the ones it depends on
2139 /// as kept.
2140 ///
2141 /// This function is called by lookForDIEsToKeep on DIEs that are
2142 /// newly discovered to be needed in the link. It recursively calls
2143 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2144 /// TraversalFlags to inform it that it's not doing the primary DIE
2145 /// tree walk.
2146 void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
2147                                           const DWARFDebugInfoEntryMinimal &Die,
2148                                           CompileUnit::DIEInfo &MyInfo,
2149                                           const DebugMapObject &DMO,
2150                                           CompileUnit &CU, bool UseODR) {
2151   const DWARFUnit &Unit = CU.getOrigUnit();
2152   MyInfo.Keep = true;
2153
2154   // First mark all the parent chain as kept.
2155   unsigned AncestorIdx = MyInfo.ParentIdx;
2156   while (!CU.getInfo(AncestorIdx).Keep) {
2157     unsigned ODRFlag = UseODR ? TF_ODR : 0;
2158     lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
2159                       TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
2160     AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2161   }
2162
2163   // Then we need to mark all the DIEs referenced by this DIE's
2164   // attributes as kept.
2165   DataExtractor Data = Unit.getDebugInfoExtractor();
2166   const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2167   uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
2168
2169   // Mark all DIEs referenced through atttributes as kept.
2170   for (const auto &AttrSpec : Abbrev->attributes()) {
2171     DWARFFormValue Val(AttrSpec.Form);
2172
2173     if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2174       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2175       continue;
2176     }
2177
2178     Val.extractValue(Data, &Offset, &Unit);
2179     CompileUnit *ReferencedCU;
2180     if (const auto *RefDIE =
2181             resolveDIEReference(*this, MutableArrayRef<CompileUnit>(Units), Val,
2182                                 Unit, Die, ReferencedCU)) {
2183       uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2184       CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2185       // If the referenced DIE has a DeclContext that has already been
2186       // emitted, then do not keep the one in this CU. We'll link to
2187       // the canonical DIE in cloneDieReferenceAttribute.
2188       // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2189       // be necessary and could be advantageously replaced by
2190       // ReferencedCU->hasODR() && CU.hasODR().
2191       // FIXME: compatibility with dsymutil-classic. There is no
2192       // reason not to unique ref_addr references.
2193       if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2194           Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2195           Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2196         continue;
2197
2198       Info.Prune = false;
2199       unsigned ODRFlag = UseODR ? TF_ODR : 0;
2200       lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
2201                         TF_Keep | TF_DependencyWalk | ODRFlag);
2202     }
2203   }
2204 }
2205
2206 /// \brief Recursively walk the \p DIE tree and look for DIEs to
2207 /// keep. Store that information in \p CU's DIEInfo.
2208 ///
2209 /// This function is the entry point of the DIE selection
2210 /// algorithm. It is expected to walk the DIE tree in file order and
2211 /// (though the mediation of its helper) call hasValidRelocation() on
2212 /// each DIE that might be a 'root DIE' (See DwarfLinker class
2213 /// comment).
2214 /// While walking the dependencies of root DIEs, this function is
2215 /// also called, but during these dependency walks the file order is
2216 /// not respected. The TF_DependencyWalk flag tells us which kind of
2217 /// traversal we are currently doing.
2218 void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2219                                     const DWARFDebugInfoEntryMinimal &Die,
2220                                     const DebugMapObject &DMO, CompileUnit &CU,
2221                                     unsigned Flags) {
2222   unsigned Idx = CU.getOrigUnit().getDIEIndex(&Die);
2223   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2224   bool AlreadyKept = MyInfo.Keep;
2225   if (MyInfo.Prune)
2226     return;
2227
2228   // If the Keep flag is set, we are marking a required DIE's
2229   // dependencies. If our target is already marked as kept, we're all
2230   // set.
2231   if ((Flags & TF_DependencyWalk) && AlreadyKept)
2232     return;
2233
2234   // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
2235   // because it would screw up the relocation finding logic.
2236   if (!(Flags & TF_DependencyWalk))
2237     Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
2238
2239   // If it is a newly kept DIE mark it as well as all its dependencies as kept.
2240   if (!AlreadyKept && (Flags & TF_Keep)) {
2241     bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2242     keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
2243   }
2244   // The TF_ParentWalk flag tells us that we are currently walking up
2245   // the parent chain of a required DIE, and we don't want to mark all
2246   // the children of the parents as kept (consider for example a
2247   // DW_TAG_namespace node in the parent chain). There are however a
2248   // set of DIE types for which we want to ignore that directive and still
2249   // walk their children.
2250   if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
2251     Flags &= ~TF_ParentWalk;
2252
2253   if (!Die.hasChildren() || (Flags & TF_ParentWalk))
2254     return;
2255
2256   for (auto *Child = Die.getFirstChild(); Child && !Child->isNULL();
2257        Child = Child->getSibling())
2258     lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
2259 }
2260
2261 /// \brief Assign an abbreviation numer to \p Abbrev.
2262 ///
2263 /// Our DIEs get freed after every DebugMapObject has been processed,
2264 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2265 /// the instances hold by the DIEs. When we encounter an abbreviation
2266 /// that we don't know, we create a permanent copy of it.
2267 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2268   // Check the set for priors.
2269   FoldingSetNodeID ID;
2270   Abbrev.Profile(ID);
2271   void *InsertToken;
2272   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2273
2274   // If it's newly added.
2275   if (InSet) {
2276     // Assign existing abbreviation number.
2277     Abbrev.setNumber(InSet->getNumber());
2278   } else {
2279     // Add to abbreviation list.
2280     Abbreviations.push_back(
2281         new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2282     for (const auto &Attr : Abbrev.getData())
2283       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2284     AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2285     // Assign the unique abbreviation number.
2286     Abbrev.setNumber(Abbreviations.size());
2287     Abbreviations.back()->setNumber(Abbreviations.size());
2288   }
2289 }
2290
2291 unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2292                                                       AttributeSpec AttrSpec,
2293                                                       const DWARFFormValue &Val,
2294                                                       const DWARFUnit &U) {
2295   // Switch everything to out of line strings.
2296   const char *String = *Val.getAsCString(&U);
2297   unsigned Offset = Linker.StringPool.getStringOffset(String);
2298   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
2299                DIEInteger(Offset));
2300   return 4;
2301 }
2302
2303 unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
2304     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2305     AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
2306     CompileUnit &Unit) {
2307   const DWARFUnit &U = Unit.getOrigUnit();
2308   uint32_t Ref = *Val.getAsReference(&U);
2309   DIE *NewRefDie = nullptr;
2310   CompileUnit *RefUnit = nullptr;
2311   DeclContext *Ctxt = nullptr;
2312
2313   const DWARFDebugInfoEntryMinimal *RefDie =
2314       resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE, RefUnit);
2315
2316   // If the referenced DIE is not found,  drop the attribute.
2317   if (!RefDie)
2318     return 0;
2319
2320   unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2321   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
2322
2323   // If we already have emitted an equivalent DeclContext, just point
2324   // at it.
2325   if (isODRAttribute(AttrSpec.Attr)) {
2326     Ctxt = RefInfo.Ctxt;
2327     if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2328       DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2329       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2330                    dwarf::DW_FORM_ref_addr, Attr);
2331       return getRefAddrSize(U);
2332     }
2333   }
2334
2335   if (!RefInfo.Clone) {
2336     assert(Ref > InputDIE.getOffset());
2337     // We haven't cloned this DIE yet. Just create an empty one and
2338     // store it. It'll get really cloned when we process it.
2339     RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
2340   }
2341   NewRefDie = RefInfo.Clone;
2342
2343   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2344       (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
2345     // We cannot currently rely on a DIEEntry to emit ref_addr
2346     // references, because the implementation calls back to DwarfDebug
2347     // to find the unit offset. (We don't have a DwarfDebug)
2348     // FIXME: we should be able to design DIEEntry reliance on
2349     // DwarfDebug away.
2350     uint64_t Attr;
2351     if (Ref < InputDIE.getOffset()) {
2352       // We must have already cloned that DIE.
2353       uint32_t NewRefOffset =
2354           RefUnit->getStartOffset() + NewRefDie->getOffset();
2355       Attr = NewRefOffset;
2356       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2357                    dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
2358     } else {
2359       // A forward reference. Note and fixup later.
2360       Attr = 0xBADDEF;
2361       Unit.noteForwardReference(
2362           NewRefDie, RefUnit, Ctxt,
2363           Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2364                        dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
2365     }
2366     return getRefAddrSize(U);
2367   }
2368
2369   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2370                dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
2371   return AttrSize;
2372 }
2373
2374 unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2375                                                      AttributeSpec AttrSpec,
2376                                                      const DWARFFormValue &Val,
2377                                                      unsigned AttrSize) {
2378   DIEValueList *Attr;
2379   DIEValue Value;
2380   DIELoc *Loc = nullptr;
2381   DIEBlock *Block = nullptr;
2382   // Just copy the block data over.
2383   if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
2384     Loc = new (DIEAlloc) DIELoc;
2385     Linker.DIELocs.push_back(Loc);
2386   } else {
2387     Block = new (DIEAlloc) DIEBlock;
2388     Linker.DIEBlocks.push_back(Block);
2389   }
2390   Attr = Loc ? static_cast<DIEValueList *>(Loc)
2391              : static_cast<DIEValueList *>(Block);
2392
2393   if (Loc)
2394     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2395                      dwarf::Form(AttrSpec.Form), Loc);
2396   else
2397     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2398                      dwarf::Form(AttrSpec.Form), Block);
2399   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2400   for (auto Byte : Bytes)
2401     Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2402                    dwarf::DW_FORM_data1, DIEInteger(Byte));
2403   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2404   // the DIE class, this if could be replaced by
2405   // Attr->setSize(Bytes.size()).
2406   if (Linker.Streamer) {
2407     auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
2408     if (Loc)
2409       Loc->ComputeSize(AsmPrinter);
2410     else
2411       Block->ComputeSize(AsmPrinter);
2412   }
2413   Die.addValue(DIEAlloc, Value);
2414   return AttrSize;
2415 }
2416
2417 unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2418     DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2419     const CompileUnit &Unit, AttributesInfo &Info) {
2420   uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
2421   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2422     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2423         Die.getTag() == dwarf::DW_TAG_lexical_block)
2424       // The low_pc of a block or inline subroutine might get
2425       // relocated because it happens to match the low_pc of the
2426       // enclosing subprogram. To prevent issues with that, always use
2427       // the low_pc from the input DIE if relocations have been applied.
2428       Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2429              Info.PCOffset;
2430     else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2431       Addr = Unit.getLowPc();
2432       if (Addr == UINT64_MAX)
2433         return 0;
2434     }
2435     Info.HasLowPc = true;
2436   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
2437     if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2438       if (uint64_t HighPc = Unit.getHighPc())
2439         Addr = HighPc;
2440       else
2441         return 0;
2442     } else
2443       // If we have a high_pc recorded for the input DIE, use
2444       // it. Otherwise (when no relocations where applied) just use the
2445       // one we just decoded.
2446       Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
2447   }
2448
2449   Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
2450                static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
2451   return Unit.getOrigUnit().getAddressByteSize();
2452 }
2453
2454 unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
2455     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2456     AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
2457     AttributesInfo &Info) {
2458   uint64_t Value;
2459   if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2460       Die.getTag() == dwarf::DW_TAG_compile_unit) {
2461     if (Unit.getLowPc() == -1ULL)
2462       return 0;
2463     // Dwarf >= 4 high_pc is an size, not an address.
2464     Value = Unit.getHighPc() - Unit.getLowPc();
2465   } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
2466     Value = *Val.getAsSectionOffset();
2467   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2468     Value = *Val.getAsSignedConstant();
2469   else if (auto OptionalValue = Val.getAsUnsignedConstant())
2470     Value = *OptionalValue;
2471   else {
2472     Linker.reportWarning(
2473         "Unsupported scalar attribute form. Dropping attribute.",
2474         &Unit.getOrigUnit(), &InputDIE);
2475     return 0;
2476   }
2477   PatchLocation Patch =
2478       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2479                    dwarf::Form(AttrSpec.Form), DIEInteger(Value));
2480   if (AttrSpec.Attr == dwarf::DW_AT_ranges)
2481     Unit.noteRangeAttribute(Die, Patch);
2482
2483   // A more generic way to check for location attributes would be
2484   // nice, but it's very unlikely that any other attribute needs a
2485   // location list.
2486   else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2487            AttrSpec.Attr == dwarf::DW_AT_frame_base)
2488     Unit.noteLocationAttribute(Patch, Info.PCOffset);
2489   else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2490     Info.IsDeclaration = true;
2491
2492   return AttrSize;
2493 }
2494
2495 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2496 /// value \p Val, and add it to \p Die.
2497 /// \returns the size of the cloned attribute.
2498 unsigned DwarfLinker::DIECloner::cloneAttribute(
2499     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2500     const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2501     AttributesInfo &Info) {
2502   const DWARFUnit &U = Unit.getOrigUnit();
2503
2504   switch (AttrSpec.Form) {
2505   case dwarf::DW_FORM_strp:
2506   case dwarf::DW_FORM_string:
2507     return cloneStringAttribute(Die, AttrSpec, Val, U);
2508   case dwarf::DW_FORM_ref_addr:
2509   case dwarf::DW_FORM_ref1:
2510   case dwarf::DW_FORM_ref2:
2511   case dwarf::DW_FORM_ref4:
2512   case dwarf::DW_FORM_ref8:
2513     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2514                                       Unit);
2515   case dwarf::DW_FORM_block:
2516   case dwarf::DW_FORM_block1:
2517   case dwarf::DW_FORM_block2:
2518   case dwarf::DW_FORM_block4:
2519   case dwarf::DW_FORM_exprloc:
2520     return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2521   case dwarf::DW_FORM_addr:
2522     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2523   case dwarf::DW_FORM_data1:
2524   case dwarf::DW_FORM_data2:
2525   case dwarf::DW_FORM_data4:
2526   case dwarf::DW_FORM_data8:
2527   case dwarf::DW_FORM_udata:
2528   case dwarf::DW_FORM_sdata:
2529   case dwarf::DW_FORM_sec_offset:
2530   case dwarf::DW_FORM_flag:
2531   case dwarf::DW_FORM_flag_present:
2532     return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2533                                 Info);
2534   default:
2535     Linker.reportWarning(
2536         "Unsupported attribute form in cloneAttribute. Dropping.", &U,
2537         &InputDIE);
2538   }
2539
2540   return 0;
2541 }
2542
2543 /// \brief Apply the valid relocations found by findValidRelocs() to
2544 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2545 /// in the debug_info section.
2546 ///
2547 /// Like for findValidRelocs(), this function must be called with
2548 /// monotonic \p BaseOffset values.
2549 ///
2550 /// \returns wether any reloc has been applied.
2551 bool DwarfLinker::RelocationManager::
2552 applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2553                  bool isLittleEndian) {
2554   assert((NextValidReloc == 0 ||
2555           BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2556          "BaseOffset should only be increasing.");
2557   if (NextValidReloc >= ValidRelocs.size())
2558     return false;
2559
2560   // Skip relocs that haven't been applied.
2561   while (NextValidReloc < ValidRelocs.size() &&
2562          ValidRelocs[NextValidReloc].Offset < BaseOffset)
2563     ++NextValidReloc;
2564
2565   bool Applied = false;
2566   uint64_t EndOffset = BaseOffset + Data.size();
2567   while (NextValidReloc < ValidRelocs.size() &&
2568          ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2569          ValidRelocs[NextValidReloc].Offset < EndOffset) {
2570     const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2571     assert(ValidReloc.Offset - BaseOffset < Data.size());
2572     assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2573     char Buf[8];
2574     uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2575     Value += ValidReloc.Addend;
2576     for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2577       unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2578       Buf[i] = uint8_t(Value >> (Index * 8));
2579     }
2580     assert(ValidReloc.Size <= sizeof(Buf));
2581     memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2582     Applied = true;
2583   }
2584
2585   return Applied;
2586 }
2587
2588 static bool isTypeTag(uint16_t Tag) {
2589   switch (Tag) {
2590   case dwarf::DW_TAG_array_type:
2591   case dwarf::DW_TAG_class_type:
2592   case dwarf::DW_TAG_enumeration_type:
2593   case dwarf::DW_TAG_pointer_type:
2594   case dwarf::DW_TAG_reference_type:
2595   case dwarf::DW_TAG_string_type:
2596   case dwarf::DW_TAG_structure_type:
2597   case dwarf::DW_TAG_subroutine_type:
2598   case dwarf::DW_TAG_typedef:
2599   case dwarf::DW_TAG_union_type:
2600   case dwarf::DW_TAG_ptr_to_member_type:
2601   case dwarf::DW_TAG_set_type:
2602   case dwarf::DW_TAG_subrange_type:
2603   case dwarf::DW_TAG_base_type:
2604   case dwarf::DW_TAG_const_type:
2605   case dwarf::DW_TAG_constant:
2606   case dwarf::DW_TAG_file_type:
2607   case dwarf::DW_TAG_namelist:
2608   case dwarf::DW_TAG_packed_type:
2609   case dwarf::DW_TAG_volatile_type:
2610   case dwarf::DW_TAG_restrict_type:
2611   case dwarf::DW_TAG_interface_type:
2612   case dwarf::DW_TAG_unspecified_type:
2613   case dwarf::DW_TAG_shared_type:
2614     return true;
2615   default:
2616     break;
2617   }
2618   return false;
2619 }
2620
2621 static bool
2622 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2623                     uint16_t Tag, bool InDebugMap, bool SkipPC,
2624                     bool InFunctionScope) {
2625   switch (AttrSpec.Attr) {
2626   default:
2627     return false;
2628   case dwarf::DW_AT_low_pc:
2629   case dwarf::DW_AT_high_pc:
2630   case dwarf::DW_AT_ranges:
2631     return SkipPC;
2632   case dwarf::DW_AT_location:
2633   case dwarf::DW_AT_frame_base:
2634     // FIXME: for some reason dsymutil-classic keeps the location
2635     // attributes when they are of block type (ie. not location
2636     // lists). This is totally wrong for globals where we will keep a
2637     // wrong address. It is mostly harmless for locals, but there is
2638     // no point in keeping these anyway when the function wasn't linked.
2639     return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2640                        !InDebugMap)) &&
2641            !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2642   }
2643 }
2644
2645 DIE *DwarfLinker::DIECloner::cloneDIE(
2646     const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2647     int64_t PCOffset, uint32_t OutOffset, unsigned Flags) {
2648   DWARFUnit &U = Unit.getOrigUnit();
2649   unsigned Idx = U.getDIEIndex(&InputDIE);
2650   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2651
2652   // Should the DIE appear in the output?
2653   if (!Unit.getInfo(Idx).Keep)
2654     return nullptr;
2655
2656   uint32_t Offset = InputDIE.getOffset();
2657   // The DIE might have been already created by a forward reference
2658   // (see cloneDieReferenceAttribute()).
2659   DIE *Die = Info.Clone;
2660   if (!Die)
2661     Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2662   assert(Die->getTag() == InputDIE.getTag());
2663   Die->setOffset(OutOffset);
2664   if ((Unit.hasODR() || Unit.isClangModule()) &&
2665       Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2666       Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2667       !Info.Ctxt->getCanonicalDIEOffset()) {
2668     // We are about to emit a DIE that is the root of its own valid
2669     // DeclContext tree. Make the current offset the canonical offset
2670     // for this context.
2671     Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2672   }
2673
2674   // Extract and clone every attribute.
2675   DataExtractor Data = U.getDebugInfoExtractor();
2676   // Point to the next DIE (generally there is always at least a NULL
2677   // entry after the current one). If this is a lone
2678   // DW_TAG_compile_unit without any children, point to the next unit.
2679   uint32_t NextOffset =
2680     (Idx + 1 < U.getNumDIEs())
2681     ? U.getDIEAtIndex(Idx + 1)->getOffset()
2682     : U.getNextUnitOffset();
2683   AttributesInfo AttrInfo;
2684
2685   // We could copy the data only if we need to aply a relocation to
2686   // it. After testing, it seems there is no performance downside to
2687   // doing the copy unconditionally, and it makes the code simpler.
2688   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2689   Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2690   // Modify the copy with relocated addresses.
2691   if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2692     // If we applied relocations, we store the value of high_pc that was
2693     // potentially stored in the input DIE. If high_pc is an address
2694     // (Dwarf version == 2), then it might have been relocated to a
2695     // totally unrelated value (because the end address in the object
2696     // file might be start address of another function which got moved
2697     // independantly by the linker). The computation of the actual
2698     // high_pc value is done in cloneAddressAttribute().
2699     AttrInfo.OrigHighPc =
2700         InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2701     // Also store the low_pc. It might get relocated in an
2702     // inline_subprogram that happens at the beginning of its
2703     // inlining function.
2704     AttrInfo.OrigLowPc =
2705         InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
2706   }
2707
2708   // Reset the Offset to 0 as we will be working on the local copy of
2709   // the data.
2710   Offset = 0;
2711
2712   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2713   Offset += getULEB128Size(Abbrev->getCode());
2714
2715   // We are entering a subprogram. Get and propagate the PCOffset.
2716   if (Die->getTag() == dwarf::DW_TAG_subprogram)
2717     PCOffset = Info.AddrAdjust;
2718   AttrInfo.PCOffset = PCOffset;
2719
2720   if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2721     Flags |= TF_InFunctionScope;
2722     if (!Info.InDebugMap)
2723       Flags |= TF_SkipPC;
2724   }
2725
2726   bool Copied = false;
2727   for (const auto &AttrSpec : Abbrev->attributes()) {
2728     if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2729                             Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2730       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2731       // FIXME: dsymutil-classic keeps the old abbreviation around
2732       // even if it's not used. We can remove this (and the copyAbbrev
2733       // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2734       if (!Copied) {
2735         copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2736         Copied = true;
2737       }
2738       continue;
2739     }
2740
2741     DWARFFormValue Val(AttrSpec.Form);
2742     uint32_t AttrSize = Offset;
2743     Val.extractValue(Data, &Offset, &U);
2744     AttrSize = Offset - AttrSize;
2745
2746     OutOffset +=
2747         cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2748   }
2749
2750   // Look for accelerator entries.
2751   uint16_t Tag = InputDIE.getTag();
2752   // FIXME: This is slightly wrong. An inline_subroutine without a
2753   // low_pc, but with AT_ranges might be interesting to get into the
2754   // accelerator tables too. For now stick with dsymutil's behavior.
2755   if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2756       Tag != dwarf::DW_TAG_compile_unit &&
2757       getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2758     if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2759       Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2760                               AttrInfo.MangledNameOffset,
2761                               Tag == dwarf::DW_TAG_inlined_subroutine);
2762     if (AttrInfo.Name)
2763       Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2764                               Tag == dwarf::DW_TAG_inlined_subroutine);
2765   } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2766              getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2767     Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2768   }
2769
2770   DIEAbbrev NewAbbrev = Die->generateAbbrev();
2771   // If a scope DIE is kept, we must have kept at least one child. If
2772   // it's not the case, we'll just be emitting one wasteful end of
2773   // children marker, but things won't break.
2774   if (InputDIE.hasChildren())
2775     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2776   // Assign a permanent abbrev number
2777   Linker.AssignAbbrev(NewAbbrev);
2778   Die->setAbbrevNumber(NewAbbrev.getNumber());
2779
2780   // Add the size of the abbreviation number to the output offset.
2781   OutOffset += getULEB128Size(Die->getAbbrevNumber());
2782
2783   if (!Abbrev->hasChildren()) {
2784     // Update our size.
2785     Die->setSize(OutOffset - Die->getOffset());
2786     return Die;
2787   }
2788
2789   // Recursively clone children.
2790   for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2791        Child = Child->getSibling()) {
2792     if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset, Flags)) {
2793       Die->addChild(Clone);
2794       OutOffset = Clone->getOffset() + Clone->getSize();
2795     }
2796   }
2797
2798   // Account for the end of children marker.
2799   OutOffset += sizeof(int8_t);
2800   // Update our size.
2801   Die->setSize(OutOffset - Die->getOffset());
2802   return Die;
2803 }
2804
2805 /// \brief Patch the input object file relevant debug_ranges entries
2806 /// and emit them in the output file. Update the relevant attributes
2807 /// to point at the new entries.
2808 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2809                                      DWARFContext &OrigDwarf) const {
2810   DWARFDebugRangeList RangeList;
2811   const auto &FunctionRanges = Unit.getFunctionRanges();
2812   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2813   DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2814                                OrigDwarf.isLittleEndian(), AddressSize);
2815   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2816   DWARFUnit &OrigUnit = Unit.getOrigUnit();
2817   const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2818   uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2819       &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2820   // Ranges addresses are based on the unit's low_pc. Compute the
2821   // offset we need to apply to adapt to the the new unit's low_pc.
2822   int64_t UnitPcOffset = 0;
2823   if (OrigLowPc != -1ULL)
2824     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2825
2826   for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2827     uint32_t Offset = RangeAttribute.get();
2828     RangeAttribute.set(Streamer->getRangesSectionSize());
2829     RangeList.extract(RangeExtractor, &Offset);
2830     const auto &Entries = RangeList.getEntries();
2831     if (!Entries.empty()) {
2832       const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2833
2834       if (CurrRange == InvalidRange ||
2835           First.StartAddress + OrigLowPc < CurrRange.start() ||
2836           First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2837         CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2838         if (CurrRange == InvalidRange ||
2839             CurrRange.start() > First.StartAddress + OrigLowPc) {
2840           reportWarning("no mapping for range.");
2841           continue;
2842         }
2843       }
2844     }
2845
2846     Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2847                                 AddressSize);
2848   }
2849 }
2850
2851 /// \brief Generate the debug_aranges entries for \p Unit and if the
2852 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2853 /// contribution for this attribute.
2854 /// FIXME: this could actually be done right in patchRangesForUnit,
2855 /// but for the sake of initial bit-for-bit compatibility with legacy
2856 /// dsymutil, we have to do it in a delayed pass.
2857 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2858   auto Attr = Unit.getUnitRangesAttribute();
2859   if (Attr)
2860     Attr->set(Streamer->getRangesSectionSize());
2861   Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2862 }
2863
2864 /// \brief Insert the new line info sequence \p Seq into the current
2865 /// set of already linked line info \p Rows.
2866 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2867                                std::vector<DWARFDebugLine::Row> &Rows) {
2868   if (Seq.empty())
2869     return;
2870
2871   if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2872     Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2873     Seq.clear();
2874     return;
2875   }
2876
2877   auto InsertPoint = std::lower_bound(
2878       Rows.begin(), Rows.end(), Seq.front(),
2879       [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2880         return LHS.Address < RHS.Address;
2881       });
2882
2883   // FIXME: this only removes the unneeded end_sequence if the
2884   // sequences have been inserted in order. using a global sort like
2885   // described in patchLineTableForUnit() and delaying the end_sequene
2886   // elimination to emitLineTableForUnit() we can get rid of all of them.
2887   if (InsertPoint != Rows.end() &&
2888       InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2889     *InsertPoint = Seq.front();
2890     Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2891   } else {
2892     Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2893   }
2894
2895   Seq.clear();
2896 }
2897
2898 static void patchStmtList(DIE &Die, DIEInteger Offset) {
2899   for (auto &V : Die.values())
2900     if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2901       V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2902       return;
2903     }
2904
2905   llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2906 }
2907
2908 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2909 /// recreate a relocated version of these for the address ranges that
2910 /// are present in the binary.
2911 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2912                                         DWARFContext &OrigDwarf) {
2913   const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
2914   uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2915       &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2916   if (StmtList == -1ULL)
2917     return;
2918
2919   // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2920   if (auto *OutputDIE = Unit.getOutputUnitDIE())
2921     patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2922
2923   // Parse the original line info for the unit.
2924   DWARFDebugLine::LineTable LineTable;
2925   uint32_t StmtOffset = StmtList;
2926   StringRef LineData = OrigDwarf.getLineSection().Data;
2927   DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2928                               Unit.getOrigUnit().getAddressByteSize());
2929   LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2930                   &StmtOffset);
2931
2932   // This vector is the output line table.
2933   std::vector<DWARFDebugLine::Row> NewRows;
2934   NewRows.reserve(LineTable.Rows.size());
2935
2936   // Current sequence of rows being extracted, before being inserted
2937   // in NewRows.
2938   std::vector<DWARFDebugLine::Row> Seq;
2939   const auto &FunctionRanges = Unit.getFunctionRanges();
2940   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2941
2942   // FIXME: This logic is meant to generate exactly the same output as
2943   // Darwin's classic dsynutil. There is a nicer way to implement this
2944   // by simply putting all the relocated line info in NewRows and simply
2945   // sorting NewRows before passing it to emitLineTableForUnit. This
2946   // should be correct as sequences for a function should stay
2947   // together in the sorted output. There are a few corner cases that
2948   // look suspicious though, and that required to implement the logic
2949   // this way. Revisit that once initial validation is finished.
2950
2951   // Iterate over the object file line info and extract the sequences
2952   // that correspond to linked functions.
2953   for (auto &Row : LineTable.Rows) {
2954     // Check wether we stepped out of the range. The range is
2955     // half-open, but consider accept the end address of the range if
2956     // it is marked as end_sequence in the input (because in that
2957     // case, the relocation offset is accurate and that entry won't
2958     // serve as the start of another function).
2959     if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2960         Row.Address > CurrRange.stop() ||
2961         (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2962       // We just stepped out of a known range. Insert a end_sequence
2963       // corresponding to the end of the range.
2964       uint64_t StopAddress = CurrRange != InvalidRange
2965                                  ? CurrRange.stop() + CurrRange.value()
2966                                  : -1ULL;
2967       CurrRange = FunctionRanges.find(Row.Address);
2968       bool CurrRangeValid =
2969           CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2970       if (!CurrRangeValid) {
2971         CurrRange = InvalidRange;
2972         if (StopAddress != -1ULL) {
2973           // Try harder by looking in the DebugMapObject function
2974           // ranges map. There are corner cases where this finds a
2975           // valid entry. It's unclear if this is right or wrong, but
2976           // for now do as dsymutil.
2977           // FIXME: Understand exactly what cases this addresses and
2978           // potentially remove it along with the Ranges map.
2979           auto Range = Ranges.lower_bound(Row.Address);
2980           if (Range != Ranges.begin() && Range != Ranges.end())
2981             --Range;
2982
2983           if (Range != Ranges.end() && Range->first <= Row.Address &&
2984               Range->second.first >= Row.Address) {
2985             StopAddress = Row.Address + Range->second.second;
2986           }
2987         }
2988       }
2989       if (StopAddress != -1ULL && !Seq.empty()) {
2990         // Insert end sequence row with the computed end address, but
2991         // the same line as the previous one.
2992         auto NextLine = Seq.back();
2993         NextLine.Address = StopAddress;
2994         NextLine.EndSequence = 1;
2995         NextLine.PrologueEnd = 0;
2996         NextLine.BasicBlock = 0;
2997         NextLine.EpilogueBegin = 0;
2998         Seq.push_back(NextLine);
2999         insertLineSequence(Seq, NewRows);
3000       }
3001
3002       if (!CurrRangeValid)
3003         continue;
3004     }
3005
3006     // Ignore empty sequences.
3007     if (Row.EndSequence && Seq.empty())
3008       continue;
3009
3010     // Relocate row address and add it to the current sequence.
3011     Row.Address += CurrRange.value();
3012     Seq.emplace_back(Row);
3013
3014     if (Row.EndSequence)
3015       insertLineSequence(Seq, NewRows);
3016   }
3017
3018   // Finished extracting, now emit the line tables.
3019   uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
3020   // FIXME: LLVM hardcodes it's prologue values. We just copy the
3021   // prologue over and that works because we act as both producer and
3022   // consumer. It would be nicer to have a real configurable line
3023   // table emitter.
3024   if (LineTable.Prologue.Version != 2 ||
3025       LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
3026       LineTable.Prologue.OpcodeBase > 13)
3027     reportWarning("line table paramters mismatch. Cannot emit.");
3028   else {
3029     MCDwarfLineTableParams Params;
3030     Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
3031     Params.DWARF2LineBase = LineTable.Prologue.LineBase;
3032     Params.DWARF2LineRange = LineTable.Prologue.LineRange;
3033     Streamer->emitLineTableForUnit(Params,
3034                                    LineData.slice(StmtList + 4, PrologueEnd),
3035                                    LineTable.Prologue.MinInstLength, NewRows,
3036                                    Unit.getOrigUnit().getAddressByteSize());
3037   }
3038 }
3039
3040 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
3041   Streamer->emitPubNamesForUnit(Unit);
3042   Streamer->emitPubTypesForUnit(Unit);
3043 }
3044
3045 /// \brief Read the frame info stored in the object, and emit the
3046 /// patched frame descriptions for the linked binary.
3047 ///
3048 /// This is actually pretty easy as the data of the CIEs and FDEs can
3049 /// be considered as black boxes and moved as is. The only thing to do
3050 /// is to patch the addresses in the headers.
3051 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3052                                           DWARFContext &OrigDwarf,
3053                                           unsigned AddrSize) {
3054   StringRef FrameData = OrigDwarf.getDebugFrameSection();
3055   if (FrameData.empty())
3056     return;
3057
3058   DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3059   uint32_t InputOffset = 0;
3060
3061   // Store the data of the CIEs defined in this object, keyed by their
3062   // offsets.
3063   DenseMap<uint32_t, StringRef> LocalCIES;
3064
3065   while (Data.isValidOffset(InputOffset)) {
3066     uint32_t EntryOffset = InputOffset;
3067     uint32_t InitialLength = Data.getU32(&InputOffset);
3068     if (InitialLength == 0xFFFFFFFF)
3069       return reportWarning("Dwarf64 bits no supported");
3070
3071     uint32_t CIEId = Data.getU32(&InputOffset);
3072     if (CIEId == 0xFFFFFFFF) {
3073       // This is a CIE, store it.
3074       StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3075       LocalCIES[EntryOffset] = CIEData;
3076       // The -4 is to account for the CIEId we just read.
3077       InputOffset += InitialLength - 4;
3078       continue;
3079     }
3080
3081     uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3082
3083     // Some compilers seem to emit frame info that doesn't start at
3084     // the function entry point, thus we can't just lookup the address
3085     // in the debug map. Use the linker's range map to see if the FDE
3086     // describes something that we can relocate.
3087     auto Range = Ranges.upper_bound(Loc);
3088     if (Range != Ranges.begin())
3089       --Range;
3090     if (Range == Ranges.end() || Range->first > Loc ||
3091         Range->second.first <= Loc) {
3092       // The +4 is to account for the size of the InitialLength field itself.
3093       InputOffset = EntryOffset + InitialLength + 4;
3094       continue;
3095     }
3096
3097     // This is an FDE, and we have a mapping.
3098     // Have we already emitted a corresponding CIE?
3099     StringRef CIEData = LocalCIES[CIEId];
3100     if (CIEData.empty())
3101       return reportWarning("Inconsistent debug_frame content. Dropping.");
3102
3103     // Look if we already emitted a CIE that corresponds to the
3104     // referenced one (the CIE data is the key of that lookup).
3105     auto IteratorInserted = EmittedCIEs.insert(
3106         std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3107     // If there is no CIE yet for this ID, emit it.
3108     if (IteratorInserted.second ||
3109         // FIXME: dsymutil-classic only caches the last used CIE for
3110         // reuse. Mimic that behavior for now. Just removing that
3111         // second half of the condition and the LastCIEOffset variable
3112         // makes the code DTRT.
3113         LastCIEOffset != IteratorInserted.first->getValue()) {
3114       LastCIEOffset = Streamer->getFrameSectionSize();
3115       IteratorInserted.first->getValue() = LastCIEOffset;
3116       Streamer->emitCIE(CIEData);
3117     }
3118
3119     // Emit the FDE with updated address and CIE pointer.
3120     // (4 + AddrSize) is the size of the CIEId + initial_location
3121     // fields that will get reconstructed by emitFDE().
3122     unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3123     Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3124                       Loc + Range->second.second,
3125                       FrameData.substr(InputOffset, FDERemainingBytes));
3126     InputOffset += FDERemainingBytes;
3127   }
3128 }
3129
3130 void DwarfLinker::DIECloner::copyAbbrev(
3131     const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
3132   DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3133                  dwarf::Form(Abbrev.hasChildren()));
3134
3135   for (const auto &Attr : Abbrev.attributes()) {
3136     uint16_t Form = Attr.Form;
3137     if (hasODR && isODRAttribute(Attr.Attr))
3138       Form = dwarf::DW_FORM_ref_addr;
3139     Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3140   }
3141
3142   Linker.AssignAbbrev(Copy);
3143 }
3144
3145 static uint64_t getDwoId(const DWARFDebugInfoEntryMinimal &CUDie,
3146                          const DWARFUnit &Unit) {
3147   uint64_t DwoId =
3148       CUDie.getAttributeValueAsUnsignedConstant(&Unit, dwarf::DW_AT_dwo_id, 0);
3149   if (!DwoId)
3150     DwoId = CUDie.getAttributeValueAsUnsignedConstant(&Unit,
3151                                                       dwarf::DW_AT_GNU_dwo_id, 0);
3152   return DwoId;
3153 }
3154
3155 bool DwarfLinker::registerModuleReference(
3156     const DWARFDebugInfoEntryMinimal &CUDie, const DWARFUnit &Unit,
3157     DebugMap &ModuleMap, unsigned Indent) {
3158   std::string PCMfile =
3159       CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_dwo_name, "");
3160   if (PCMfile.empty())
3161     PCMfile =
3162         CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_GNU_dwo_name, "");
3163   if (PCMfile.empty())
3164     return false;
3165
3166   // Clang module DWARF skeleton CUs abuse this for the path to the module.
3167   std::string PCMpath =
3168       CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_comp_dir, "");
3169   uint64_t DwoId = getDwoId(CUDie, Unit);
3170
3171   std::string Name =
3172       CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_name, "");
3173   if (Name.empty()) {
3174     reportWarning("Anonymous module skeleton CU for " + PCMfile);
3175     return true;
3176   }
3177
3178   if (Options.Verbose) {
3179     outs().indent(Indent);
3180     outs() << "Found clang module reference " << PCMfile;
3181   }
3182
3183   auto Cached = ClangModules.find(PCMfile);
3184   if (Cached != ClangModules.end()) {
3185     if (Cached->second != DwoId)
3186       reportWarning(Twine("hash mismatch: this object file was built against a "
3187                           "different version of the module ") + PCMfile);
3188     if (Options.Verbose)
3189       outs() << " [cached].\n";
3190     return true;
3191   }
3192   if (Options.Verbose)
3193     outs() << " ...\n";
3194
3195   // Cyclic dependencies are disallowed by Clang, but we still
3196   // shouldn't run into an infinite loop, so mark it as processed now.
3197   ClangModules.insert({PCMfile, DwoId});
3198   loadClangModule(PCMfile, PCMpath, Name, DwoId, ModuleMap, Indent + 2);
3199   return true;
3200 }
3201
3202 ErrorOr<const object::ObjectFile &>
3203 DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3204                         const DebugMap &Map) {
3205   auto ErrOrObjs =
3206       BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
3207   if (std::error_code EC = ErrOrObjs.getError()) {
3208     reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3209     return EC;
3210   }
3211   auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3212   if (std::error_code EC = ErrOrObj.getError())
3213     reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3214   return ErrOrObj;
3215 }
3216
3217 void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
3218                                   StringRef ModuleName, uint64_t DwoId,
3219                                   DebugMap &ModuleMap, unsigned Indent) {
3220   SmallString<80> Path(Options.PrependPath);
3221   if (sys::path::is_relative(Filename))
3222     sys::path::append(Path, ModulePath, Filename);
3223   else
3224     sys::path::append(Path, Filename);
3225   BinaryHolder ObjHolder(Options.Verbose);
3226   auto &Obj =
3227       ModuleMap.addDebugMapObject(Path, sys::TimeValue::PosixZeroTime());
3228   auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
3229   if (!ErrOrObj) {
3230     ClangModules.erase(ClangModules.find(Filename));
3231     return;
3232   }
3233
3234   std::unique_ptr<CompileUnit> Unit;
3235
3236   // Setup access to the debug info.
3237   DWARFContextInMemory DwarfContext(*ErrOrObj);
3238   RelocationManager RelocMgr(*this);
3239   for (const auto &CU : DwarfContext.compile_units()) {
3240     auto *CUDie = CU->getUnitDIE(false);
3241     // Recursively get all modules imported by this one.
3242     if (!registerModuleReference(*CUDie, *CU, ModuleMap, Indent)) {
3243       if (Unit) {
3244         errs() << Filename << ": Clang modules are expected to have exactly"
3245                << " 1 compile unit.\n";
3246         exitDsymutil(1);
3247       }
3248       if (getDwoId(*CUDie, *CU) != DwoId)
3249         reportWarning(
3250             Twine("hash mismatch: this object file was built against a "
3251                   "different version of the module ") + Filename);
3252
3253       // Add this module.
3254       Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
3255                                             ModuleName);
3256       Unit->setHasInterestingContent();
3257       analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3258                          ODRContexts);
3259       // Keep everything.
3260       Unit->markEverythingAsKept();
3261     }
3262   }
3263   if (Options.Verbose) {
3264     outs().indent(Indent);
3265     outs() << "cloning .debug_info from " << Filename << "\n";
3266   }
3267
3268   DIECloner(*this, RelocMgr, DIEAlloc, MutableArrayRef<CompileUnit>(*Unit),
3269             Options)
3270       .cloneAllCompileUnits(DwarfContext);
3271 }
3272
3273 void DwarfLinker::DIECloner::cloneAllCompileUnits(
3274     DWARFContextInMemory &DwarfContext) {
3275   if (!Linker.Streamer)
3276     return;
3277
3278   for (auto &CurrentUnit : CompileUnits) {
3279     const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
3280     CurrentUnit.setStartOffset(Linker.OutputDebugInfoSize);
3281     DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PC offset */,
3282                               11 /* Unit Header size */, 0);
3283     CurrentUnit.setOutputUnitDIE(OutputDIE);
3284     Linker.OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3285     if (Linker.Options.NoOutput)
3286       continue;
3287     // FIXME: for compatibility with the classic dsymutil, we emit
3288     // an empty line table for the unit, even if the unit doesn't
3289     // actually exist in the DIE tree.
3290     Linker.patchLineTableForUnit(CurrentUnit, DwarfContext);
3291     if (!OutputDIE)
3292       continue;
3293     Linker.patchRangesForUnit(CurrentUnit, DwarfContext);
3294     Linker.Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3295     Linker.emitAcceleratorEntriesForUnit(CurrentUnit);
3296   }
3297
3298   if (Linker.Options.NoOutput)
3299     return;
3300
3301   // Emit all the compile unit's debug information.
3302   for (auto &CurrentUnit : CompileUnits) {
3303     Linker.generateUnitRanges(CurrentUnit);
3304     CurrentUnit.fixupForwardReferences();
3305     Linker.Streamer->emitCompileUnitHeader(CurrentUnit);
3306     if (!CurrentUnit.getOutputUnitDIE())
3307       continue;
3308     Linker.Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3309   }
3310 }
3311
3312 bool DwarfLinker::link(const DebugMap &Map) {
3313
3314   if (!createStreamer(Map.getTriple(), OutputFilename))
3315     return false;
3316
3317   // Size of the DIEs (and headers) generated for the linked output.
3318   OutputDebugInfoSize = 0;
3319   // A unique ID that identifies each compile unit.
3320   UnitID = 0;
3321   DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3322
3323   for (const auto &Obj : Map.objects()) {
3324     CurrentDebugObject = Obj.get();
3325
3326     if (Options.Verbose)
3327       outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
3328     auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3329     if (!ErrOrObj)
3330       continue;
3331
3332     // Look for relocations that correspond to debug map entries.
3333     RelocationManager RelocMgr(*this);
3334     if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
3335       if (Options.Verbose)
3336         outs() << "No valid relocations found. Skipping.\n";
3337       continue;
3338     }
3339
3340     // Setup access to the debug info.
3341     DWARFContextInMemory DwarfContext(*ErrOrObj);
3342     startDebugObject(DwarfContext, *Obj);
3343
3344     // In a first phase, just read in the debug info and load all clang modules.
3345     for (const auto &CU : DwarfContext.compile_units()) {
3346       auto *CUDie = CU->getUnitDIE(false);
3347       if (Options.Verbose) {
3348         outs() << "Input compilation unit:";
3349         CUDie->dump(outs(), CU.get(), 0);
3350       }
3351
3352       if (!registerModuleReference(*CUDie, *CU, ModuleMap))
3353         Units.emplace_back(*CU, UnitID++, !Options.NoODR, "");
3354     }
3355
3356     // Now build the DIE parent links that we will use during the next phase.
3357     for (auto &CurrentUnit : Units)
3358       analyzeContextInfo(CurrentUnit.getOrigUnit().getUnitDIE(), 0, CurrentUnit,
3359                          &ODRContexts.getRoot(), StringPool, ODRContexts);
3360
3361     // Then mark all the DIEs that need to be present in the linked
3362     // output and collect some information about them. Note that this
3363     // loop can not be merged with the previous one becaue cross-cu
3364     // references require the ParentIdx to be setup for every CU in
3365     // the object file before calling this.
3366     for (auto &CurrentUnit : Units)
3367       lookForDIEsToKeep(RelocMgr, *CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
3368                         CurrentUnit, 0);
3369
3370     // The calls to applyValidRelocs inside cloneDIE will walk the
3371     // reloc array again (in the same way findValidRelocsInDebugInfo()
3372     // did). We need to reset the NextValidReloc index to the beginning.
3373     RelocMgr.resetValidRelocs();
3374     if (RelocMgr.hasValidRelocs())
3375       DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3376           .cloneAllCompileUnits(DwarfContext);
3377     if (!Options.NoOutput && !Units.empty())
3378       patchFrameInfoForObject(*Obj, DwarfContext,
3379                               Units[0].getOrigUnit().getAddressByteSize());
3380
3381     // Clean-up before starting working on the next object.
3382     endDebugObject();
3383   }
3384
3385   // Emit everything that's global.
3386   if (!Options.NoOutput) {
3387     Streamer->emitAbbrevs(Abbreviations);
3388     Streamer->emitStrings(StringPool);
3389   }
3390
3391   return Options.NoOutput ? true : Streamer->finish(Map);
3392 }
3393 }
3394
3395 /// \brief Get the offset of string \p S in the string table. This
3396 /// can insert a new element or return the offset of a preexisitng
3397 /// one.
3398 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3399   if (S.empty() && !Strings.empty())
3400     return 0;
3401
3402   std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3403   MapTy::iterator It;
3404   bool Inserted;
3405
3406   // A non-empty string can't be at offset 0, so if we have an entry
3407   // with a 0 offset, it must be a previously interned string.
3408   std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3409   if (Inserted || It->getValue().first == 0) {
3410     // Set offset and chain at the end of the entries list.
3411     It->getValue().first = CurrentEndOffset;
3412     CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3413     Last->getValue().second = &*It;
3414     Last = &*It;
3415   }
3416   return It->getValue().first;
3417 }
3418
3419 /// \brief Put \p S into the StringMap so that it gets permanent
3420 /// storage, but do not actually link it in the chain of elements
3421 /// that go into the output section. A latter call to
3422 /// getStringOffset() with the same string will chain it though.
3423 StringRef NonRelocatableStringpool::internString(StringRef S) {
3424   std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3425   auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3426   return InsertResult.first->getKey();
3427 }
3428
3429 void warn(const Twine &Warning, const Twine &Context) {
3430   errs() << Twine("while processing ") + Context + ":\n";
3431   errs() << Twine("warning: ") + Warning + "\n";
3432 }
3433
3434 bool error(const Twine &Error, const Twine &Context) {
3435   errs() << Twine("while processing ") + Context + ":\n";
3436   errs() << Twine("error: ") + Error + "\n";
3437   return false;
3438 }
3439
3440 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3441                const LinkOptions &Options) {
3442   DwarfLinker Linker(OutputFilename, Options);
3443   return Linker.link(DM);
3444 }
3445 }
3446 }