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