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