1 //=== DWARFLinker.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/DWARFLinker/DWARFLinker.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/BitVector.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/CodeGen/NonRelocatableStringpool.h"
14 #include "llvm/DWARFLinker/DWARFLinkerDeclContext.h"
15 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
16 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
17 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
20 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
21 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
22 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
23 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
24 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
25 #include "llvm/MC/MCDwarf.h"
26 #include "llvm/Support/DataExtractor.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ErrorOr.h"
30 #include "llvm/Support/FormatVariadic.h"
31 #include "llvm/Support/LEB128.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/ThreadPool.h"
34 #include <vector>
35 
36 namespace llvm {
37 
38 /// Hold the input and output of the debug info size in bytes.
39 struct DebugInfoSize {
40   uint64_t Input;
41   uint64_t Output;
42 };
43 
44 /// Compute the total size of the debug info.
getDebugInfoSize(DWARFContext & Dwarf)45 static uint64_t getDebugInfoSize(DWARFContext &Dwarf) {
46   uint64_t Size = 0;
47   for (auto &Unit : Dwarf.compile_units()) {
48     Size += Unit->getLength();
49   }
50   return Size;
51 }
52 
53 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
54 /// CompileUnit object instead.
getUnitForOffset(const UnitListTy & Units,uint64_t Offset)55 static CompileUnit *getUnitForOffset(const UnitListTy &Units, uint64_t Offset) {
56   auto CU = llvm::upper_bound(
57       Units, Offset, [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
58         return LHS < RHS->getOrigUnit().getNextUnitOffset();
59       });
60   return CU != Units.end() ? CU->get() : nullptr;
61 }
62 
63 /// Resolve the DIE attribute reference that has been extracted in \p RefValue.
64 /// The resulting DIE might be in another CompileUnit which is stored into \p
65 /// ReferencedCU. \returns null if resolving fails for any reason.
resolveDIEReference(const DWARFFile & File,const UnitListTy & Units,const DWARFFormValue & RefValue,const DWARFDie & DIE,CompileUnit * & RefCU)66 DWARFDie DWARFLinker::resolveDIEReference(const DWARFFile &File,
67                                           const UnitListTy &Units,
68                                           const DWARFFormValue &RefValue,
69                                           const DWARFDie &DIE,
70                                           CompileUnit *&RefCU) {
71   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
72   uint64_t RefOffset = *RefValue.getAsReference();
73   if ((RefCU = getUnitForOffset(Units, RefOffset)))
74     if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
75       // In a file with broken references, an attribute might point to a NULL
76       // DIE.
77       if (!RefDie.isNULL())
78         return RefDie;
79     }
80 
81   reportWarning("could not find referenced DIE", File, &DIE);
82   return DWARFDie();
83 }
84 
85 /// \returns whether the passed \a Attr type might contain a DIE reference
86 /// suitable for ODR uniquing.
isODRAttribute(uint16_t Attr)87 static bool isODRAttribute(uint16_t Attr) {
88   switch (Attr) {
89   default:
90     return false;
91   case dwarf::DW_AT_type:
92   case dwarf::DW_AT_containing_type:
93   case dwarf::DW_AT_specification:
94   case dwarf::DW_AT_abstract_origin:
95   case dwarf::DW_AT_import:
96     return true;
97   }
98   llvm_unreachable("Improper attribute.");
99 }
100 
isTypeTag(uint16_t Tag)101 static bool isTypeTag(uint16_t Tag) {
102   switch (Tag) {
103   case dwarf::DW_TAG_array_type:
104   case dwarf::DW_TAG_class_type:
105   case dwarf::DW_TAG_enumeration_type:
106   case dwarf::DW_TAG_pointer_type:
107   case dwarf::DW_TAG_reference_type:
108   case dwarf::DW_TAG_string_type:
109   case dwarf::DW_TAG_structure_type:
110   case dwarf::DW_TAG_subroutine_type:
111   case dwarf::DW_TAG_typedef:
112   case dwarf::DW_TAG_union_type:
113   case dwarf::DW_TAG_ptr_to_member_type:
114   case dwarf::DW_TAG_set_type:
115   case dwarf::DW_TAG_subrange_type:
116   case dwarf::DW_TAG_base_type:
117   case dwarf::DW_TAG_const_type:
118   case dwarf::DW_TAG_constant:
119   case dwarf::DW_TAG_file_type:
120   case dwarf::DW_TAG_namelist:
121   case dwarf::DW_TAG_packed_type:
122   case dwarf::DW_TAG_volatile_type:
123   case dwarf::DW_TAG_restrict_type:
124   case dwarf::DW_TAG_atomic_type:
125   case dwarf::DW_TAG_interface_type:
126   case dwarf::DW_TAG_unspecified_type:
127   case dwarf::DW_TAG_shared_type:
128   case dwarf::DW_TAG_immutable_type:
129     return true;
130   default:
131     break;
132   }
133   return false;
134 }
135 
136 AddressesMap::~AddressesMap() = default;
137 
138 DwarfEmitter::~DwarfEmitter() = default;
139 
StripTemplateParameters(StringRef Name)140 static Optional<StringRef> StripTemplateParameters(StringRef Name) {
141   // We are looking for template parameters to strip from Name. e.g.
142   //
143   //  operator<<B>
144   //
145   // We look for > at the end but if it does not contain any < then we
146   // have something like operator>>. We check for the operator<=> case.
147   if (!Name.endswith(">") || Name.count("<") == 0 || Name.endswith("<=>"))
148     return {};
149 
150   // How many < until we have the start of the template parameters.
151   size_t NumLeftAnglesToSkip = 1;
152 
153   // If we have operator<=> then we need to skip its < as well.
154   NumLeftAnglesToSkip += Name.count("<=>");
155 
156   size_t RightAngleCount = Name.count('>');
157   size_t LeftAngleCount = Name.count('<');
158 
159   // If we have more < than > we have operator< or operator<<
160   // we to account for their < as well.
161   if (LeftAngleCount > RightAngleCount)
162     NumLeftAnglesToSkip += LeftAngleCount - RightAngleCount;
163 
164   size_t StartOfTemplate = 0;
165   while (NumLeftAnglesToSkip--)
166     StartOfTemplate = Name.find('<', StartOfTemplate) + 1;
167 
168   return Name.substr(0, StartOfTemplate - 1);
169 }
170 
getDIENames(const DWARFDie & Die,AttributesInfo & Info,OffsetsStringPool & StringPool,bool StripTemplate)171 bool DWARFLinker::DIECloner::getDIENames(const DWARFDie &Die,
172                                          AttributesInfo &Info,
173                                          OffsetsStringPool &StringPool,
174                                          bool StripTemplate) {
175   // This function will be called on DIEs having low_pcs and
176   // ranges. As getting the name might be more expansive, filter out
177   // blocks directly.
178   if (Die.getTag() == dwarf::DW_TAG_lexical_block)
179     return false;
180 
181   if (!Info.MangledName)
182     if (const char *MangledName = Die.getLinkageName())
183       Info.MangledName = StringPool.getEntry(MangledName);
184 
185   if (!Info.Name)
186     if (const char *Name = Die.getShortName())
187       Info.Name = StringPool.getEntry(Name);
188 
189   if (!Info.MangledName)
190     Info.MangledName = Info.Name;
191 
192   if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
193     StringRef Name = Info.Name.getString();
194     if (Optional<StringRef> StrippedName = StripTemplateParameters(Name))
195       Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName);
196   }
197 
198   return Info.Name || Info.MangledName;
199 }
200 
201 /// Resolve the relative path to a build artifact referenced by DWARF by
202 /// applying DW_AT_comp_dir.
resolveRelativeObjectPath(SmallVectorImpl<char> & Buf,DWARFDie CU)203 static void resolveRelativeObjectPath(SmallVectorImpl<char> &Buf, DWARFDie CU) {
204   sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
205 }
206 
207 /// Collect references to parseable Swift interfaces in imported
208 /// DW_TAG_module blocks.
analyzeImportedModule(const DWARFDie & DIE,CompileUnit & CU,swiftInterfacesMap * ParseableSwiftInterfaces,std::function<void (const Twine &,const DWARFDie &)> ReportWarning)209 static void analyzeImportedModule(
210     const DWARFDie &DIE, CompileUnit &CU,
211     swiftInterfacesMap *ParseableSwiftInterfaces,
212     std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
213   if (CU.getLanguage() != dwarf::DW_LANG_Swift)
214     return;
215 
216   if (!ParseableSwiftInterfaces)
217     return;
218 
219   StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
220   if (!Path.endswith(".swiftinterface"))
221     return;
222   // Don't track interfaces that are part of the SDK.
223   StringRef SysRoot = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_sysroot));
224   if (SysRoot.empty())
225     SysRoot = CU.getSysRoot();
226   if (!SysRoot.empty() && Path.startswith(SysRoot))
227     return;
228   Optional<const char*> Name = dwarf::toString(DIE.find(dwarf::DW_AT_name));
229   if (!Name)
230     return;
231   auto &Entry = (*ParseableSwiftInterfaces)[*Name];
232   // The prepend path is applied later when copying.
233   DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
234   SmallString<128> ResolvedPath;
235   if (sys::path::is_relative(Path))
236     resolveRelativeObjectPath(ResolvedPath, CUDie);
237   sys::path::append(ResolvedPath, Path);
238   if (!Entry.empty() && Entry != ResolvedPath)
239     ReportWarning(Twine("Conflicting parseable interfaces for Swift Module ") +
240                       *Name + ": " + Entry + " and " + Path,
241                   DIE);
242   Entry = std::string(ResolvedPath.str());
243 }
244 
245 /// The distinct types of work performed by the work loop in
246 /// analyzeContextInfo.
247 enum class ContextWorklistItemType : uint8_t {
248   AnalyzeContextInfo,
249   UpdateChildPruning,
250   UpdatePruning,
251 };
252 
253 /// This class represents an item in the work list. The type defines what kind
254 /// of work needs to be performed when processing the current item. Everything
255 /// but the Type and Die fields are optional based on the type.
256 struct ContextWorklistItem {
257   DWARFDie Die;
258   unsigned ParentIdx;
259   union {
260     CompileUnit::DIEInfo *OtherInfo;
261     DeclContext *Context;
262   };
263   ContextWorklistItemType Type;
264   bool InImportedModule;
265 
ContextWorklistItemllvm::ContextWorklistItem266   ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T,
267                       CompileUnit::DIEInfo *OtherInfo = nullptr)
268       : Die(Die), ParentIdx(0), OtherInfo(OtherInfo), Type(T),
269         InImportedModule(false) {}
270 
ContextWorklistItemllvm::ContextWorklistItem271   ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx,
272                       bool InImportedModule)
273       : Die(Die), ParentIdx(ParentIdx), Context(Context),
274         Type(ContextWorklistItemType::AnalyzeContextInfo),
275         InImportedModule(InImportedModule) {}
276 };
277 
updatePruning(const DWARFDie & Die,CompileUnit & CU,uint64_t ModulesEndOffset)278 static bool updatePruning(const DWARFDie &Die, CompileUnit &CU,
279                           uint64_t ModulesEndOffset) {
280   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
281 
282   // Prune this DIE if it is either a forward declaration inside a
283   // DW_TAG_module or a DW_TAG_module that contains nothing but
284   // forward declarations.
285   Info.Prune &= (Die.getTag() == dwarf::DW_TAG_module) ||
286                 (isTypeTag(Die.getTag()) &&
287                  dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0));
288 
289   // Only prune forward declarations inside a DW_TAG_module for which a
290   // definition exists elsewhere.
291   if (ModulesEndOffset == 0)
292     Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
293   else
294     Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
295                   Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
296 
297   return Info.Prune;
298 }
299 
updateChildPruning(const DWARFDie & Die,CompileUnit & CU,CompileUnit::DIEInfo & ChildInfo)300 static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU,
301                                CompileUnit::DIEInfo &ChildInfo) {
302   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
303   Info.Prune &= ChildInfo.Prune;
304 }
305 
306 /// Recursive helper to build the global DeclContext information and
307 /// gather the child->parent relationships in the original compile unit.
308 ///
309 /// This function uses the same work list approach as lookForDIEsToKeep.
310 ///
311 /// \return true when this DIE and all of its children are only
312 /// forward declarations to types defined in external clang modules
313 /// (i.e., forward declarations that are children of a DW_TAG_module).
analyzeContextInfo(const DWARFDie & DIE,unsigned ParentIdx,CompileUnit & CU,DeclContext * CurrentDeclContext,DeclContextTree & Contexts,uint64_t ModulesEndOffset,swiftInterfacesMap * ParseableSwiftInterfaces,std::function<void (const Twine &,const DWARFDie &)> ReportWarning,bool InImportedModule=false)314 static bool analyzeContextInfo(
315     const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
316     DeclContext *CurrentDeclContext, DeclContextTree &Contexts,
317     uint64_t ModulesEndOffset, swiftInterfacesMap *ParseableSwiftInterfaces,
318     std::function<void(const Twine &, const DWARFDie &)> ReportWarning,
319     bool InImportedModule = false) {
320   // LIFO work list.
321   std::vector<ContextWorklistItem> Worklist;
322   Worklist.emplace_back(DIE, CurrentDeclContext, ParentIdx, InImportedModule);
323 
324   while (!Worklist.empty()) {
325     ContextWorklistItem Current = Worklist.back();
326     Worklist.pop_back();
327 
328     switch (Current.Type) {
329     case ContextWorklistItemType::UpdatePruning:
330       updatePruning(Current.Die, CU, ModulesEndOffset);
331       continue;
332     case ContextWorklistItemType::UpdateChildPruning:
333       updateChildPruning(Current.Die, CU, *Current.OtherInfo);
334       continue;
335     case ContextWorklistItemType::AnalyzeContextInfo:
336       break;
337     }
338 
339     unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
340     CompileUnit::DIEInfo &Info = CU.getInfo(Idx);
341 
342     // Clang imposes an ODR on modules(!) regardless of the language:
343     //  "The module-id should consist of only a single identifier,
344     //   which provides the name of the module being defined. Each
345     //   module shall have a single definition."
346     //
347     // This does not extend to the types inside the modules:
348     //  "[I]n C, this implies that if two structs are defined in
349     //   different submodules with the same name, those two types are
350     //   distinct types (but may be compatible types if their
351     //   definitions match)."
352     //
353     // We treat non-C++ modules like namespaces for this reason.
354     if (Current.Die.getTag() == dwarf::DW_TAG_module &&
355         Current.ParentIdx == 0 &&
356         dwarf::toString(Current.Die.find(dwarf::DW_AT_name), "") !=
357             CU.getClangModuleName()) {
358       Current.InImportedModule = true;
359       analyzeImportedModule(Current.Die, CU, ParseableSwiftInterfaces,
360                             ReportWarning);
361     }
362 
363     Info.ParentIdx = Current.ParentIdx;
364     Info.InModuleScope = CU.isClangModule() || Current.InImportedModule;
365     if (CU.hasODR() || Info.InModuleScope) {
366       if (Current.Context) {
367         auto PtrInvalidPair = Contexts.getChildDeclContext(
368             *Current.Context, Current.Die, CU, Info.InModuleScope);
369         Current.Context = PtrInvalidPair.getPointer();
370         Info.Ctxt =
371             PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
372         if (Info.Ctxt)
373           Info.Ctxt->setDefinedInClangModule(Info.InModuleScope);
374       } else
375         Info.Ctxt = Current.Context = nullptr;
376     }
377 
378     Info.Prune = Current.InImportedModule;
379     // Add children in reverse order to the worklist to effectively process
380     // them in order.
381     Worklist.emplace_back(Current.Die, ContextWorklistItemType::UpdatePruning);
382     for (auto Child : reverse(Current.Die.children())) {
383       CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
384       Worklist.emplace_back(
385           Current.Die, ContextWorklistItemType::UpdateChildPruning, &ChildInfo);
386       Worklist.emplace_back(Child, Current.Context, Idx,
387                             Current.InImportedModule);
388     }
389   }
390 
391   return CU.getInfo(DIE).Prune;
392 }
393 
dieNeedsChildrenToBeMeaningful(uint32_t Tag)394 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
395   switch (Tag) {
396   default:
397     return false;
398   case dwarf::DW_TAG_class_type:
399   case dwarf::DW_TAG_common_block:
400   case dwarf::DW_TAG_lexical_block:
401   case dwarf::DW_TAG_structure_type:
402   case dwarf::DW_TAG_subprogram:
403   case dwarf::DW_TAG_subroutine_type:
404   case dwarf::DW_TAG_union_type:
405     return true;
406   }
407   llvm_unreachable("Invalid Tag");
408 }
409 
cleanupAuxiliarryData(LinkContext & Context)410 void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
411   Context.clear();
412 
413   for (DIEBlock *I : DIEBlocks)
414     I->~DIEBlock();
415   for (DIELoc *I : DIELocs)
416     I->~DIELoc();
417 
418   DIEBlocks.clear();
419   DIELocs.clear();
420   DIEAlloc.Reset();
421 }
422 
423 /// Check if a variable describing DIE should be kept.
424 /// \returns updated TraversalFlags.
shouldKeepVariableDIE(AddressesMap & RelocMgr,const DWARFDie & DIE,CompileUnit::DIEInfo & MyInfo,unsigned Flags)425 unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
426                                             const DWARFDie &DIE,
427                                             CompileUnit::DIEInfo &MyInfo,
428                                             unsigned Flags) {
429   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
430 
431   // Global variables with constant value can always be kept.
432   if (!(Flags & TF_InFunctionScope) &&
433       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
434     MyInfo.InDebugMap = true;
435     return Flags | TF_Keep;
436   }
437 
438   // See if there is a relocation to a valid debug map entry inside this
439   // variable's location. The order is important here. We want to always check
440   // if the variable has a valid relocation, so that the DIEInfo is filled.
441   // However, we don't want a static variable in a function to force us to keep
442   // the enclosing function, unless requested explicitly.
443   const bool HasLiveMemoryLocation = RelocMgr.isLiveVariable(DIE, MyInfo);
444   if (!HasLiveMemoryLocation || ((Flags & TF_InFunctionScope) &&
445                                  !LLVM_UNLIKELY(Options.KeepFunctionForStatic)))
446     return Flags;
447 
448   if (Options.Verbose) {
449     outs() << "Keeping variable DIE:";
450     DIDumpOptions DumpOpts;
451     DumpOpts.ChildRecurseDepth = 0;
452     DumpOpts.Verbose = Options.Verbose;
453     DIE.dump(outs(), 8 /* Indent */, DumpOpts);
454   }
455 
456   return Flags | TF_Keep;
457 }
458 
459 /// Check if a function describing DIE should be kept.
460 /// \returns updated TraversalFlags.
shouldKeepSubprogramDIE(AddressesMap & RelocMgr,RangesTy & Ranges,const DWARFDie & DIE,const DWARFFile & File,CompileUnit & Unit,CompileUnit::DIEInfo & MyInfo,unsigned Flags)461 unsigned DWARFLinker::shouldKeepSubprogramDIE(
462     AddressesMap &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE,
463     const DWARFFile &File, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
464     unsigned Flags) {
465   Flags |= TF_InFunctionScope;
466 
467   auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
468   if (!LowPc)
469     return Flags;
470 
471   assert(LowPc && "low_pc attribute is not an address.");
472   if (!RelocMgr.isLiveSubprogram(DIE, MyInfo))
473     return Flags;
474 
475   if (Options.Verbose) {
476     outs() << "Keeping subprogram DIE:";
477     DIDumpOptions DumpOpts;
478     DumpOpts.ChildRecurseDepth = 0;
479     DumpOpts.Verbose = Options.Verbose;
480     DIE.dump(outs(), 8 /* Indent */, DumpOpts);
481   }
482 
483   if (DIE.getTag() == dwarf::DW_TAG_label) {
484     if (Unit.hasLabelAt(*LowPc))
485       return Flags;
486 
487     DWARFUnit &OrigUnit = Unit.getOrigUnit();
488     // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
489     // that don't fall into the CU's aranges. This is wrong IMO. Debug info
490     // generation bugs aside, this is really wrong in the case of labels, where
491     // a label marking the end of a function will have a PC == CU's high_pc.
492     if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
493             .value_or(UINT64_MAX) <= LowPc)
494       return Flags;
495     Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
496     return Flags | TF_Keep;
497   }
498 
499   Flags |= TF_Keep;
500 
501   Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
502   if (!HighPc) {
503     reportWarning("Function without high_pc. Range will be discarded.\n", File,
504                   &DIE);
505     return Flags;
506   }
507   if (*LowPc > *HighPc) {
508     reportWarning("low_pc greater than high_pc. Range will be discarded.\n",
509                   File, &DIE);
510     return Flags;
511   }
512 
513   // Replace the debug map range with a more accurate one.
514   Ranges.insert({*LowPc, *HighPc}, MyInfo.AddrAdjust);
515   Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
516   return Flags;
517 }
518 
519 /// Check if a DIE should be kept.
520 /// \returns updated TraversalFlags.
shouldKeepDIE(AddressesMap & RelocMgr,RangesTy & Ranges,const DWARFDie & DIE,const DWARFFile & File,CompileUnit & Unit,CompileUnit::DIEInfo & MyInfo,unsigned Flags)521 unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, RangesTy &Ranges,
522                                     const DWARFDie &DIE, const DWARFFile &File,
523                                     CompileUnit &Unit,
524                                     CompileUnit::DIEInfo &MyInfo,
525                                     unsigned Flags) {
526   switch (DIE.getTag()) {
527   case dwarf::DW_TAG_constant:
528   case dwarf::DW_TAG_variable:
529     return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
530   case dwarf::DW_TAG_subprogram:
531   case dwarf::DW_TAG_label:
532     return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, File, Unit, MyInfo,
533                                    Flags);
534   case dwarf::DW_TAG_base_type:
535     // DWARF Expressions may reference basic types, but scanning them
536     // is expensive. Basic types are tiny, so just keep all of them.
537   case dwarf::DW_TAG_imported_module:
538   case dwarf::DW_TAG_imported_declaration:
539   case dwarf::DW_TAG_imported_unit:
540     // We always want to keep these.
541     return Flags | TF_Keep;
542   default:
543     break;
544   }
545 
546   return Flags;
547 }
548 
549 /// Helper that updates the completeness of the current DIE based on the
550 /// completeness of one of its children. It depends on the incompleteness of
551 /// the children already being computed.
updateChildIncompleteness(const DWARFDie & Die,CompileUnit & CU,CompileUnit::DIEInfo & ChildInfo)552 static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU,
553                                       CompileUnit::DIEInfo &ChildInfo) {
554   switch (Die.getTag()) {
555   case dwarf::DW_TAG_structure_type:
556   case dwarf::DW_TAG_class_type:
557   case dwarf::DW_TAG_union_type:
558     break;
559   default:
560     return;
561   }
562 
563   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
564 
565   if (ChildInfo.Incomplete || ChildInfo.Prune)
566     MyInfo.Incomplete = true;
567 }
568 
569 /// Helper that updates the completeness of the current DIE based on the
570 /// completeness of the DIEs it references. It depends on the incompleteness of
571 /// the referenced DIE already being computed.
updateRefIncompleteness(const DWARFDie & Die,CompileUnit & CU,CompileUnit::DIEInfo & RefInfo)572 static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU,
573                                     CompileUnit::DIEInfo &RefInfo) {
574   switch (Die.getTag()) {
575   case dwarf::DW_TAG_typedef:
576   case dwarf::DW_TAG_member:
577   case dwarf::DW_TAG_reference_type:
578   case dwarf::DW_TAG_ptr_to_member_type:
579   case dwarf::DW_TAG_pointer_type:
580     break;
581   default:
582     return;
583   }
584 
585   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
586 
587   if (MyInfo.Incomplete)
588     return;
589 
590   if (RefInfo.Incomplete)
591     MyInfo.Incomplete = true;
592 }
593 
594 /// Look at the children of the given DIE and decide whether they should be
595 /// kept.
lookForChildDIEsToKeep(const DWARFDie & Die,CompileUnit & CU,unsigned Flags,SmallVectorImpl<WorklistItem> & Worklist)596 void DWARFLinker::lookForChildDIEsToKeep(
597     const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
598     SmallVectorImpl<WorklistItem> &Worklist) {
599   // The TF_ParentWalk flag tells us that we are currently walking up the
600   // parent chain of a required DIE, and we don't want to mark all the children
601   // of the parents as kept (consider for example a DW_TAG_namespace node in
602   // the parent chain). There are however a set of DIE types for which we want
603   // to ignore that directive and still walk their children.
604   if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
605     Flags &= ~DWARFLinker::TF_ParentWalk;
606 
607   // We're finished if this DIE has no children or we're walking the parent
608   // chain.
609   if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
610     return;
611 
612   // Add children in reverse order to the worklist to effectively process them
613   // in order.
614   for (auto Child : reverse(Die.children())) {
615     // Add a worklist item before every child to calculate incompleteness right
616     // after the current child is processed.
617     CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
618     Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness,
619                           &ChildInfo);
620     Worklist.emplace_back(Child, CU, Flags);
621   }
622 }
623 
isODRCanonicalCandidate(const DWARFDie & Die,CompileUnit & CU)624 static bool isODRCanonicalCandidate(const DWARFDie &Die, CompileUnit &CU) {
625   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
626 
627   if (!Info.Ctxt || (Die.getTag() == dwarf::DW_TAG_namespace))
628     return false;
629 
630   if (!CU.hasODR() && !Info.InModuleScope)
631     return false;
632 
633   return !Info.Incomplete && Info.Ctxt != CU.getInfo(Info.ParentIdx).Ctxt;
634 }
635 
markODRCanonicalDie(const DWARFDie & Die,CompileUnit & CU)636 void DWARFLinker::markODRCanonicalDie(const DWARFDie &Die, CompileUnit &CU) {
637   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
638 
639   Info.ODRMarkingDone = true;
640   if (Info.Keep && isODRCanonicalCandidate(Die, CU) &&
641       !Info.Ctxt->hasCanonicalDIE())
642     Info.Ctxt->setHasCanonicalDIE();
643 }
644 
645 /// Look at DIEs referenced by the given DIE and decide whether they should be
646 /// kept. All DIEs referenced though attributes should be kept.
lookForRefDIEsToKeep(const DWARFDie & Die,CompileUnit & CU,unsigned Flags,const UnitListTy & Units,const DWARFFile & File,SmallVectorImpl<WorklistItem> & Worklist)647 void DWARFLinker::lookForRefDIEsToKeep(
648     const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
649     const UnitListTy &Units, const DWARFFile &File,
650     SmallVectorImpl<WorklistItem> &Worklist) {
651   bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk)
652                     ? (Flags & DWARFLinker::TF_ODR)
653                     : CU.hasODR();
654   DWARFUnit &Unit = CU.getOrigUnit();
655   DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
656   const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
657   uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
658 
659   SmallVector<std::pair<DWARFDie, CompileUnit &>, 4> ReferencedDIEs;
660   for (const auto &AttrSpec : Abbrev->attributes()) {
661     DWARFFormValue Val(AttrSpec.Form);
662     if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
663         AttrSpec.Attr == dwarf::DW_AT_sibling) {
664       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
665                                 Unit.getFormParams());
666       continue;
667     }
668 
669     Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
670     CompileUnit *ReferencedCU;
671     if (auto RefDie =
672             resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
673       CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefDie);
674       // If the referenced DIE has a DeclContext that has already been
675       // emitted, then do not keep the one in this CU. We'll link to
676       // the canonical DIE in cloneDieReferenceAttribute.
677       //
678       // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
679       // be necessary and could be advantageously replaced by
680       // ReferencedCU->hasODR() && CU.hasODR().
681       //
682       // FIXME: compatibility with dsymutil-classic. There is no
683       // reason not to unique ref_addr references.
684       if (AttrSpec.Form != dwarf::DW_FORM_ref_addr &&
685           isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
686           Info.Ctxt->hasCanonicalDIE())
687         continue;
688 
689       // Keep a module forward declaration if there is no definition.
690       if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
691             Info.Ctxt->hasCanonicalDIE()))
692         Info.Prune = false;
693       ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
694     }
695   }
696 
697   unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
698 
699   // Add referenced DIEs in reverse order to the worklist to effectively
700   // process them in order.
701   for (auto &P : reverse(ReferencedDIEs)) {
702     // Add a worklist item before every child to calculate incompleteness right
703     // after the current child is processed.
704     CompileUnit::DIEInfo &Info = P.second.getInfo(P.first);
705     Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
706                           &Info);
707     Worklist.emplace_back(P.first, P.second,
708                           DWARFLinker::TF_Keep |
709                               DWARFLinker::TF_DependencyWalk | ODRFlag);
710   }
711 }
712 
713 /// Look at the parent of the given DIE and decide whether they should be kept.
lookForParentDIEsToKeep(unsigned AncestorIdx,CompileUnit & CU,unsigned Flags,SmallVectorImpl<WorklistItem> & Worklist)714 void DWARFLinker::lookForParentDIEsToKeep(
715     unsigned AncestorIdx, CompileUnit &CU, unsigned Flags,
716     SmallVectorImpl<WorklistItem> &Worklist) {
717   // Stop if we encounter an ancestor that's already marked as kept.
718   if (CU.getInfo(AncestorIdx).Keep)
719     return;
720 
721   DWARFUnit &Unit = CU.getOrigUnit();
722   DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx);
723   Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
724   Worklist.emplace_back(ParentDIE, CU, Flags);
725 }
726 
727 /// Recursively walk the \p DIE tree and look for DIEs to keep. Store that
728 /// information in \p CU's DIEInfo.
729 ///
730 /// This function is the entry point of the DIE selection algorithm. It is
731 /// expected to walk the DIE tree in file order and (though the mediation of
732 /// its helper) call hasValidRelocation() on each DIE that might be a 'root
733 /// DIE' (See DwarfLinker class comment).
734 ///
735 /// While walking the dependencies of root DIEs, this function is also called,
736 /// but during these dependency walks the file order is not respected. The
737 /// TF_DependencyWalk flag tells us which kind of traversal we are currently
738 /// doing.
739 ///
740 /// The recursive algorithm is implemented iteratively as a work list because
741 /// very deep recursion could exhaust the stack for large projects. The work
742 /// list acts as a scheduler for different types of work that need to be
743 /// performed.
744 ///
745 /// The recursive nature of the algorithm is simulated by running the "main"
746 /// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs
747 /// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or
748 /// fixing up a computed property (UpdateChildIncompleteness,
749 /// UpdateRefIncompleteness).
750 ///
751 /// The return value indicates whether the DIE is incomplete.
lookForDIEsToKeep(AddressesMap & AddressesMap,RangesTy & Ranges,const UnitListTy & Units,const DWARFDie & Die,const DWARFFile & File,CompileUnit & Cu,unsigned Flags)752 void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
753                                     RangesTy &Ranges, const UnitListTy &Units,
754                                     const DWARFDie &Die, const DWARFFile &File,
755                                     CompileUnit &Cu, unsigned Flags) {
756   // LIFO work list.
757   SmallVector<WorklistItem, 4> Worklist;
758   Worklist.emplace_back(Die, Cu, Flags);
759 
760   while (!Worklist.empty()) {
761     WorklistItem Current = Worklist.pop_back_val();
762 
763     // Look at the worklist type to decide what kind of work to perform.
764     switch (Current.Type) {
765     case WorklistItemType::UpdateChildIncompleteness:
766       updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
767       continue;
768     case WorklistItemType::UpdateRefIncompleteness:
769       updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
770       continue;
771     case WorklistItemType::LookForChildDIEsToKeep:
772       lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
773       continue;
774     case WorklistItemType::LookForRefDIEsToKeep:
775       lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
776                            Worklist);
777       continue;
778     case WorklistItemType::LookForParentDIEsToKeep:
779       lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
780                               Worklist);
781       continue;
782     case WorklistItemType::MarkODRCanonicalDie:
783       markODRCanonicalDie(Current.Die, Current.CU);
784       continue;
785     case WorklistItemType::LookForDIEsToKeep:
786       break;
787     }
788 
789     unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
790     CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
791 
792     if (MyInfo.Prune)
793       continue;
794 
795     // If the Keep flag is set, we are marking a required DIE's dependencies.
796     // If our target is already marked as kept, we're all set.
797     bool AlreadyKept = MyInfo.Keep;
798     if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
799       continue;
800 
801     // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
802     // because it would screw up the relocation finding logic.
803     if (!(Current.Flags & TF_DependencyWalk))
804       Current.Flags = shouldKeepDIE(AddressesMap, Ranges, Current.Die, File,
805                                     Current.CU, MyInfo, Current.Flags);
806 
807     // We need to mark context for the canonical die in the end of normal
808     // traversing(not TF_DependencyWalk) or after normal traversing if die
809     // was not marked as kept.
810     if (!(Current.Flags & TF_DependencyWalk) ||
811         (MyInfo.ODRMarkingDone && !MyInfo.Keep)) {
812       if (Current.CU.hasODR() || MyInfo.InModuleScope)
813         Worklist.emplace_back(Current.Die, Current.CU,
814                               WorklistItemType::MarkODRCanonicalDie);
815     }
816 
817     // Finish by looking for child DIEs. Because of the LIFO worklist we need
818     // to schedule that work before any subsequent items are added to the
819     // worklist.
820     Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
821                           WorklistItemType::LookForChildDIEsToKeep);
822 
823     if (AlreadyKept || !(Current.Flags & TF_Keep))
824       continue;
825 
826     // If it is a newly kept DIE mark it as well as all its dependencies as
827     // kept.
828     MyInfo.Keep = true;
829 
830     // We're looking for incomplete types.
831     MyInfo.Incomplete =
832         Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
833         Current.Die.getTag() != dwarf::DW_TAG_member &&
834         dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0);
835 
836     // After looking at the parent chain, look for referenced DIEs. Because of
837     // the LIFO worklist we need to schedule that work before any subsequent
838     // items are added to the worklist.
839     Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
840                           WorklistItemType::LookForRefDIEsToKeep);
841 
842     bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
843                                                       : Current.CU.hasODR();
844     unsigned ODRFlag = UseOdr ? TF_ODR : 0;
845     unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
846 
847     // Now schedule the parent walk.
848     Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
849   }
850 }
851 
852 /// Assign an abbreviation number to \p Abbrev.
853 ///
854 /// Our DIEs get freed after every DebugMapObject has been processed,
855 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
856 /// the instances hold by the DIEs. When we encounter an abbreviation
857 /// that we don't know, we create a permanent copy of it.
assignAbbrev(DIEAbbrev & Abbrev)858 void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
859   // Check the set for priors.
860   FoldingSetNodeID ID;
861   Abbrev.Profile(ID);
862   void *InsertToken;
863   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
864 
865   // If it's newly added.
866   if (InSet) {
867     // Assign existing abbreviation number.
868     Abbrev.setNumber(InSet->getNumber());
869   } else {
870     // Add to abbreviation list.
871     Abbreviations.push_back(
872         std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
873     for (const auto &Attr : Abbrev.getData())
874       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
875     AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
876     // Assign the unique abbreviation number.
877     Abbrev.setNumber(Abbreviations.size());
878     Abbreviations.back()->setNumber(Abbreviations.size());
879   }
880 }
881 
cloneStringAttribute(DIE & Die,AttributeSpec AttrSpec,const DWARFFormValue & Val,const DWARFUnit &,OffsetsStringPool & StringPool,AttributesInfo & Info)882 unsigned DWARFLinker::DIECloner::cloneStringAttribute(
883     DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
884     const DWARFUnit &, OffsetsStringPool &StringPool, AttributesInfo &Info) {
885   Optional<const char *> String = dwarf::toString(Val);
886   if (!String)
887     return 0;
888 
889   // Switch everything to out of line strings.
890   auto StringEntry = StringPool.getEntry(*String);
891 
892   // Update attributes info.
893   if (AttrSpec.Attr == dwarf::DW_AT_name)
894     Info.Name = StringEntry;
895   else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
896            AttrSpec.Attr == dwarf::DW_AT_linkage_name)
897     Info.MangledName = StringEntry;
898 
899   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
900                DIEInteger(StringEntry.getOffset()));
901 
902   return 4;
903 }
904 
cloneDieReferenceAttribute(DIE & Die,const DWARFDie & InputDIE,AttributeSpec AttrSpec,unsigned AttrSize,const DWARFFormValue & Val,const DWARFFile & File,CompileUnit & Unit)905 unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
906     DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
907     unsigned AttrSize, const DWARFFormValue &Val, const DWARFFile &File,
908     CompileUnit &Unit) {
909   const DWARFUnit &U = Unit.getOrigUnit();
910   uint64_t Ref = *Val.getAsReference();
911 
912   DIE *NewRefDie = nullptr;
913   CompileUnit *RefUnit = nullptr;
914 
915   DWARFDie RefDie =
916       Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
917 
918   // If the referenced DIE is not found,  drop the attribute.
919   if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
920     return 0;
921 
922   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
923 
924   // If we already have emitted an equivalent DeclContext, just point
925   // at it.
926   if (isODRAttribute(AttrSpec.Attr) && RefInfo.Ctxt &&
927       RefInfo.Ctxt->getCanonicalDIEOffset()) {
928     assert(RefInfo.Ctxt->hasCanonicalDIE() &&
929            "Offset to canonical die is set, but context is not marked");
930     DIEInteger Attr(RefInfo.Ctxt->getCanonicalDIEOffset());
931     Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
932                  dwarf::DW_FORM_ref_addr, Attr);
933     return U.getRefAddrByteSize();
934   }
935 
936   if (!RefInfo.Clone) {
937     assert(Ref > InputDIE.getOffset());
938     // We haven't cloned this DIE yet. Just create an empty one and
939     // store it. It'll get really cloned when we process it.
940     RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
941   }
942   NewRefDie = RefInfo.Clone;
943 
944   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
945       (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
946     // We cannot currently rely on a DIEEntry to emit ref_addr
947     // references, because the implementation calls back to DwarfDebug
948     // to find the unit offset. (We don't have a DwarfDebug)
949     // FIXME: we should be able to design DIEEntry reliance on
950     // DwarfDebug away.
951     uint64_t Attr;
952     if (Ref < InputDIE.getOffset()) {
953       // We must have already cloned that DIE.
954       uint32_t NewRefOffset =
955           RefUnit->getStartOffset() + NewRefDie->getOffset();
956       Attr = NewRefOffset;
957       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
958                    dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
959     } else {
960       // A forward reference. Note and fixup later.
961       Attr = 0xBADDEF;
962       Unit.noteForwardReference(
963           NewRefDie, RefUnit, RefInfo.Ctxt,
964           Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
965                        dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
966     }
967     return U.getRefAddrByteSize();
968   }
969 
970   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
971                dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
972 
973   return AttrSize;
974 }
975 
cloneExpression(DataExtractor & Data,DWARFExpression Expression,const DWARFFile & File,CompileUnit & Unit,SmallVectorImpl<uint8_t> & OutputBuffer)976 void DWARFLinker::DIECloner::cloneExpression(
977     DataExtractor &Data, DWARFExpression Expression, const DWARFFile &File,
978     CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) {
979   using Encoding = DWARFExpression::Operation::Encoding;
980 
981   uint64_t OpOffset = 0;
982   for (auto &Op : Expression) {
983     auto Description = Op.getDescription();
984     // DW_OP_const_type is variable-length and has 3
985     // operands. DWARFExpression thus far only supports 2.
986     auto Op0 = Description.Op[0];
987     auto Op1 = Description.Op[1];
988     if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) ||
989         (Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1))
990       Linker.reportWarning("Unsupported DW_OP encoding.", File);
991 
992     if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) ||
993         (Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) {
994       // This code assumes that the other non-typeref operand fits into 1 byte.
995       assert(OpOffset < Op.getEndOffset());
996       uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
997       assert(ULEBsize <= 16);
998 
999       // Copy over the operation.
1000       OutputBuffer.push_back(Op.getCode());
1001       uint64_t RefOffset;
1002       if (Op1 == Encoding::SizeNA) {
1003         RefOffset = Op.getRawOperand(0);
1004       } else {
1005         OutputBuffer.push_back(Op.getRawOperand(0));
1006         RefOffset = Op.getRawOperand(1);
1007       }
1008       uint32_t Offset = 0;
1009       // Look up the base type. For DW_OP_convert, the operand may be 0 to
1010       // instead indicate the generic type. The same holds for
1011       // DW_OP_reinterpret, which is currently not supported.
1012       if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
1013         RefOffset += Unit.getOrigUnit().getOffset();
1014         auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
1015         CompileUnit::DIEInfo &Info = Unit.getInfo(RefDie);
1016         if (DIE *Clone = Info.Clone)
1017           Offset = Clone->getOffset();
1018         else
1019           Linker.reportWarning(
1020               "base type ref doesn't point to DW_TAG_base_type.", File);
1021       }
1022       uint8_t ULEB[16];
1023       unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
1024       if (RealSize > ULEBsize) {
1025         // Emit the generic type as a fallback.
1026         RealSize = encodeULEB128(0, ULEB, ULEBsize);
1027         Linker.reportWarning("base type ref doesn't fit.", File);
1028       }
1029       assert(RealSize == ULEBsize && "padding failed");
1030       ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
1031       OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
1032     } else {
1033       // Copy over everything else unmodified.
1034       StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
1035       OutputBuffer.append(Bytes.begin(), Bytes.end());
1036     }
1037     OpOffset = Op.getEndOffset();
1038   }
1039 }
1040 
cloneBlockAttribute(DIE & Die,const DWARFFile & File,CompileUnit & Unit,AttributeSpec AttrSpec,const DWARFFormValue & Val,unsigned AttrSize,bool IsLittleEndian)1041 unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
1042     DIE &Die, const DWARFFile &File, CompileUnit &Unit, AttributeSpec AttrSpec,
1043     const DWARFFormValue &Val, unsigned AttrSize, bool IsLittleEndian) {
1044   DIEValueList *Attr;
1045   DIEValue Value;
1046   DIELoc *Loc = nullptr;
1047   DIEBlock *Block = nullptr;
1048   if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1049     Loc = new (DIEAlloc) DIELoc;
1050     Linker.DIELocs.push_back(Loc);
1051   } else {
1052     Block = new (DIEAlloc) DIEBlock;
1053     Linker.DIEBlocks.push_back(Block);
1054   }
1055   Attr = Loc ? static_cast<DIEValueList *>(Loc)
1056              : static_cast<DIEValueList *>(Block);
1057 
1058   if (Loc)
1059     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1060                      dwarf::Form(AttrSpec.Form), Loc);
1061   else
1062     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1063                      dwarf::Form(AttrSpec.Form), Block);
1064 
1065   // If the block is a DWARF Expression, clone it into the temporary
1066   // buffer using cloneExpression(), otherwise copy the data directly.
1067   SmallVector<uint8_t, 32> Buffer;
1068   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1069   if (DWARFAttribute::mayHaveLocationExpr(AttrSpec.Attr) &&
1070       (Val.isFormClass(DWARFFormValue::FC_Block) ||
1071        Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
1072     DWARFUnit &OrigUnit = Unit.getOrigUnit();
1073     DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
1074                        IsLittleEndian, OrigUnit.getAddressByteSize());
1075     DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(),
1076                          OrigUnit.getFormParams().Format);
1077     cloneExpression(Data, Expr, File, Unit, Buffer);
1078     Bytes = Buffer;
1079   }
1080   for (auto Byte : Bytes)
1081     Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1082                    dwarf::DW_FORM_data1, DIEInteger(Byte));
1083 
1084   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1085   // the DIE class, this "if" could be replaced by
1086   // Attr->setSize(Bytes.size()).
1087   if (Loc)
1088     Loc->setSize(Bytes.size());
1089   else
1090     Block->setSize(Bytes.size());
1091 
1092   Die.addValue(DIEAlloc, Value);
1093   return AttrSize;
1094 }
1095 
cloneAddressAttribute(DIE & Die,AttributeSpec AttrSpec,const DWARFFormValue & Val,const CompileUnit & Unit,AttributesInfo & Info)1096 unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
1097     DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1098     const CompileUnit &Unit, AttributesInfo &Info) {
1099   if (LLVM_UNLIKELY(Linker.Options.Update)) {
1100     if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1101       Info.HasLowPc = true;
1102     Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1103                  dwarf::Form(AttrSpec.Form), DIEInteger(Val.getRawUValue()));
1104     return Unit.getOrigUnit().getAddressByteSize();
1105   }
1106 
1107   dwarf::Form Form = AttrSpec.Form;
1108   uint64_t Addr = 0;
1109   if (Form == dwarf::DW_FORM_addrx) {
1110     if (Optional<uint64_t> AddrOffsetSectionBase =
1111             Unit.getOrigUnit().getAddrOffsetSectionBase()) {
1112       uint64_t StartOffset = *AddrOffsetSectionBase + Val.getRawUValue();
1113       uint64_t EndOffset =
1114           StartOffset + Unit.getOrigUnit().getAddressByteSize();
1115       if (llvm::Expected<uint64_t> RelocAddr =
1116               ObjFile.Addresses->relocateIndexedAddr(StartOffset, EndOffset))
1117         Addr = *RelocAddr;
1118       else
1119         Linker.reportWarning(toString(RelocAddr.takeError()), ObjFile);
1120     } else
1121       Linker.reportWarning("no base offset for address table", ObjFile);
1122 
1123     // If this is an indexed address emit the debug_info address.
1124     Form = dwarf::DW_FORM_addr;
1125   } else
1126     Addr = *Val.getAsAddress();
1127 
1128   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1129     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1130         Die.getTag() == dwarf::DW_TAG_lexical_block ||
1131         Die.getTag() == dwarf::DW_TAG_label) {
1132       // The low_pc of a block or inline subroutine might get
1133       // relocated because it happens to match the low_pc of the
1134       // enclosing subprogram. To prevent issues with that, always use
1135       // the low_pc from the input DIE if relocations have been applied.
1136       Addr = (Info.OrigLowPc != std::numeric_limits<uint64_t>::max()
1137                   ? Info.OrigLowPc
1138                   : Addr) +
1139              Info.PCOffset;
1140     } else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1141       Addr = Unit.getLowPc();
1142       if (Addr == std::numeric_limits<uint64_t>::max())
1143         return 0;
1144     }
1145     Info.HasLowPc = true;
1146   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1147     if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1148       if (uint64_t HighPc = Unit.getHighPc())
1149         Addr = HighPc;
1150       else
1151         return 0;
1152     } else
1153       // If we have a high_pc recorded for the input DIE, use
1154       // it. Otherwise (when no relocations where applied) just use the
1155       // one we just decoded.
1156       Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1157   } else if (AttrSpec.Attr == dwarf::DW_AT_call_return_pc) {
1158     // Relocate a return PC address within a call site entry.
1159     if (Die.getTag() == dwarf::DW_TAG_call_site)
1160       Addr = (Info.OrigCallReturnPc ? Info.OrigCallReturnPc : Addr) +
1161              Info.PCOffset;
1162   } else if (AttrSpec.Attr == dwarf::DW_AT_call_pc) {
1163     // Relocate the address of a branch instruction within a call site entry.
1164     if (Die.getTag() == dwarf::DW_TAG_call_site)
1165       Addr = (Info.OrigCallPc ? Info.OrigCallPc : Addr) + Info.PCOffset;
1166   }
1167 
1168   Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1169                static_cast<dwarf::Form>(Form), DIEInteger(Addr));
1170   return Unit.getOrigUnit().getAddressByteSize();
1171 }
1172 
cloneScalarAttribute(DIE & Die,const DWARFDie & InputDIE,const DWARFFile & File,CompileUnit & Unit,AttributeSpec AttrSpec,const DWARFFormValue & Val,unsigned AttrSize,AttributesInfo & Info)1173 unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
1174     DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1175     CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1176     unsigned AttrSize, AttributesInfo &Info) {
1177   uint64_t Value;
1178 
1179   if (LLVM_UNLIKELY(Linker.Options.Update)) {
1180     if (auto OptionalValue = Val.getAsUnsignedConstant())
1181       Value = *OptionalValue;
1182     else if (auto OptionalValue = Val.getAsSignedConstant())
1183       Value = *OptionalValue;
1184     else if (auto OptionalValue = Val.getAsSectionOffset())
1185       Value = *OptionalValue;
1186     else {
1187       Linker.reportWarning(
1188           "Unsupported scalar attribute form. Dropping attribute.", File,
1189           &InputDIE);
1190       return 0;
1191     }
1192     if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1193       Info.IsDeclaration = true;
1194     Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1195                  dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1196     return AttrSize;
1197   }
1198 
1199   if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1200       Die.getTag() == dwarf::DW_TAG_compile_unit) {
1201     if (Unit.getLowPc() == -1ULL)
1202       return 0;
1203     // Dwarf >= 4 high_pc is an size, not an address.
1204     Value = Unit.getHighPc() - Unit.getLowPc();
1205   } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1206     Value = *Val.getAsSectionOffset();
1207   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1208     Value = *Val.getAsSignedConstant();
1209   else if (auto OptionalValue = Val.getAsUnsignedConstant())
1210     Value = *OptionalValue;
1211   else {
1212     Linker.reportWarning(
1213         "Unsupported scalar attribute form. Dropping attribute.", File,
1214         &InputDIE);
1215     return 0;
1216   }
1217   PatchLocation Patch =
1218       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1219                    dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1220   if (AttrSpec.Attr == dwarf::DW_AT_ranges) {
1221     Unit.noteRangeAttribute(Die, Patch);
1222     Info.HasRanges = true;
1223   }
1224 
1225   // A more generic way to check for location attributes would be
1226   // nice, but it's very unlikely that any other attribute needs a
1227   // location list.
1228   // FIXME: use DWARFAttribute::mayHaveLocationDescription().
1229   else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1230            AttrSpec.Attr == dwarf::DW_AT_frame_base) {
1231     Unit.noteLocationAttribute(Patch, Info.PCOffset);
1232   } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1233     Info.IsDeclaration = true;
1234 
1235   return AttrSize;
1236 }
1237 
1238 /// Clone \p InputDIE's attribute described by \p AttrSpec with
1239 /// value \p Val, and add it to \p Die.
1240 /// \returns the size of the cloned attribute.
cloneAttribute(DIE & Die,const DWARFDie & InputDIE,const DWARFFile & File,CompileUnit & Unit,OffsetsStringPool & StringPool,const DWARFFormValue & Val,const AttributeSpec AttrSpec,unsigned AttrSize,AttributesInfo & Info,bool IsLittleEndian)1241 unsigned DWARFLinker::DIECloner::cloneAttribute(
1242     DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1243     CompileUnit &Unit, OffsetsStringPool &StringPool, const DWARFFormValue &Val,
1244     const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info,
1245     bool IsLittleEndian) {
1246   const DWARFUnit &U = Unit.getOrigUnit();
1247 
1248   switch (AttrSpec.Form) {
1249   case dwarf::DW_FORM_strp:
1250   case dwarf::DW_FORM_string:
1251   case dwarf::DW_FORM_strx:
1252   case dwarf::DW_FORM_strx1:
1253   case dwarf::DW_FORM_strx2:
1254   case dwarf::DW_FORM_strx3:
1255   case dwarf::DW_FORM_strx4:
1256     return cloneStringAttribute(Die, AttrSpec, Val, U, StringPool, Info);
1257   case dwarf::DW_FORM_ref_addr:
1258   case dwarf::DW_FORM_ref1:
1259   case dwarf::DW_FORM_ref2:
1260   case dwarf::DW_FORM_ref4:
1261   case dwarf::DW_FORM_ref8:
1262     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1263                                       File, Unit);
1264   case dwarf::DW_FORM_block:
1265   case dwarf::DW_FORM_block1:
1266   case dwarf::DW_FORM_block2:
1267   case dwarf::DW_FORM_block4:
1268   case dwarf::DW_FORM_exprloc:
1269     return cloneBlockAttribute(Die, File, Unit, AttrSpec, Val, AttrSize,
1270                                IsLittleEndian);
1271   case dwarf::DW_FORM_addr:
1272   case dwarf::DW_FORM_addrx:
1273     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1274   case dwarf::DW_FORM_data1:
1275   case dwarf::DW_FORM_data2:
1276   case dwarf::DW_FORM_data4:
1277   case dwarf::DW_FORM_data8:
1278   case dwarf::DW_FORM_udata:
1279   case dwarf::DW_FORM_sdata:
1280   case dwarf::DW_FORM_sec_offset:
1281   case dwarf::DW_FORM_flag:
1282   case dwarf::DW_FORM_flag_present:
1283     return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1284                                 AttrSize, Info);
1285   default:
1286     Linker.reportWarning("Unsupported attribute form " +
1287                              dwarf::FormEncodingString(AttrSpec.Form) +
1288                              " in cloneAttribute. Dropping.",
1289                          File, &InputDIE);
1290   }
1291 
1292   return 0;
1293 }
1294 
isObjCSelector(StringRef Name)1295 static bool isObjCSelector(StringRef Name) {
1296   return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') &&
1297          (Name[1] == '[');
1298 }
1299 
addObjCAccelerator(CompileUnit & Unit,const DIE * Die,DwarfStringPoolEntryRef Name,OffsetsStringPool & StringPool,bool SkipPubSection)1300 void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1301                                                 const DIE *Die,
1302                                                 DwarfStringPoolEntryRef Name,
1303                                                 OffsetsStringPool &StringPool,
1304                                                 bool SkipPubSection) {
1305   assert(isObjCSelector(Name.getString()) && "not an objc selector");
1306   // Objective C method or class function.
1307   // "- [Class(Category) selector :withArg ...]"
1308   StringRef ClassNameStart(Name.getString().drop_front(2));
1309   size_t FirstSpace = ClassNameStart.find(' ');
1310   if (FirstSpace == StringRef::npos)
1311     return;
1312 
1313   StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1);
1314   if (!SelectorStart.size())
1315     return;
1316 
1317   StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1);
1318   Unit.addNameAccelerator(Die, StringPool.getEntry(Selector), SkipPubSection);
1319 
1320   // Add an entry for the class name that points to this
1321   // method/class function.
1322   StringRef ClassName(ClassNameStart.data(), FirstSpace);
1323   Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassName), SkipPubSection);
1324 
1325   if (ClassName[ClassName.size() - 1] == ')') {
1326     size_t OpenParens = ClassName.find('(');
1327     if (OpenParens != StringRef::npos) {
1328       StringRef ClassNameNoCategory(ClassName.data(), OpenParens);
1329       Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassNameNoCategory),
1330                               SkipPubSection);
1331 
1332       std::string MethodNameNoCategory(Name.getString().data(), OpenParens + 2);
1333       // FIXME: The missing space here may be a bug, but
1334       //        dsymutil-classic also does it this way.
1335       MethodNameNoCategory.append(std::string(SelectorStart));
1336       Unit.addNameAccelerator(Die, StringPool.getEntry(MethodNameNoCategory),
1337                               SkipPubSection);
1338     }
1339   }
1340 }
1341 
1342 static bool
shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,uint16_t Tag,bool InDebugMap,bool SkipPC,bool InFunctionScope)1343 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
1344                     uint16_t Tag, bool InDebugMap, bool SkipPC,
1345                     bool InFunctionScope) {
1346   switch (AttrSpec.Attr) {
1347   default:
1348     return false;
1349   case dwarf::DW_AT_low_pc:
1350   case dwarf::DW_AT_high_pc:
1351   case dwarf::DW_AT_ranges:
1352     return SkipPC;
1353   case dwarf::DW_AT_str_offsets_base:
1354     // FIXME: Use the string offset table with Dwarf 5.
1355     return true;
1356   case dwarf::DW_AT_location:
1357   case dwarf::DW_AT_frame_base:
1358     // FIXME: for some reason dsymutil-classic keeps the location attributes
1359     // when they are of block type (i.e. not location lists). This is totally
1360     // wrong for globals where we will keep a wrong address. It is mostly
1361     // harmless for locals, but there is no point in keeping these anyway when
1362     // the function wasn't linked.
1363     return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
1364                        !InDebugMap)) &&
1365            !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
1366   }
1367 }
1368 
cloneDIE(const DWARFDie & InputDIE,const DWARFFile & File,CompileUnit & Unit,OffsetsStringPool & StringPool,int64_t PCOffset,uint32_t OutOffset,unsigned Flags,bool IsLittleEndian,DIE * Die)1369 DIE *DWARFLinker::DIECloner::cloneDIE(const DWARFDie &InputDIE,
1370                                       const DWARFFile &File, CompileUnit &Unit,
1371                                       OffsetsStringPool &StringPool,
1372                                       int64_t PCOffset, uint32_t OutOffset,
1373                                       unsigned Flags, bool IsLittleEndian,
1374                                       DIE *Die) {
1375   DWARFUnit &U = Unit.getOrigUnit();
1376   unsigned Idx = U.getDIEIndex(InputDIE);
1377   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1378 
1379   // Should the DIE appear in the output?
1380   if (!Unit.getInfo(Idx).Keep)
1381     return nullptr;
1382 
1383   uint64_t Offset = InputDIE.getOffset();
1384   assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
1385   if (!Die) {
1386     // The DIE might have been already created by a forward reference
1387     // (see cloneDieReferenceAttribute()).
1388     if (!Info.Clone)
1389       Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
1390     Die = Info.Clone;
1391   }
1392 
1393   assert(Die->getTag() == InputDIE.getTag());
1394   Die->setOffset(OutOffset);
1395   if (isODRCanonicalCandidate(InputDIE, Unit) && Info.Ctxt &&
1396       (Info.Ctxt->getCanonicalDIEOffset() == 0)) {
1397     if (!Info.Ctxt->hasCanonicalDIE())
1398       Info.Ctxt->setHasCanonicalDIE();
1399     // We are about to emit a DIE that is the root of its own valid
1400     // DeclContext tree. Make the current offset the canonical offset
1401     // for this context.
1402     Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
1403   }
1404 
1405   // Extract and clone every attribute.
1406   DWARFDataExtractor Data = U.getDebugInfoExtractor();
1407   // Point to the next DIE (generally there is always at least a NULL
1408   // entry after the current one). If this is a lone
1409   // DW_TAG_compile_unit without any children, point to the next unit.
1410   uint64_t NextOffset = (Idx + 1 < U.getNumDIEs())
1411                             ? U.getDIEAtIndex(Idx + 1).getOffset()
1412                             : U.getNextUnitOffset();
1413   AttributesInfo AttrInfo;
1414 
1415   // We could copy the data only if we need to apply a relocation to it. After
1416   // testing, it seems there is no performance downside to doing the copy
1417   // unconditionally, and it makes the code simpler.
1418   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1419   Data =
1420       DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1421 
1422   // Modify the copy with relocated addresses.
1423   if (ObjFile.Addresses->applyValidRelocs(DIECopy, Offset,
1424                                           Data.isLittleEndian())) {
1425     // If we applied relocations, we store the value of high_pc that was
1426     // potentially stored in the input DIE. If high_pc is an address
1427     // (Dwarf version == 2), then it might have been relocated to a
1428     // totally unrelated value (because the end address in the object
1429     // file might be start address of another function which got moved
1430     // independently by the linker). The computation of the actual
1431     // high_pc value is done in cloneAddressAttribute().
1432     AttrInfo.OrigHighPc =
1433         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0);
1434     // Also store the low_pc. It might get relocated in an
1435     // inline_subprogram that happens at the beginning of its
1436     // inlining function.
1437     AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc),
1438                                           std::numeric_limits<uint64_t>::max());
1439     AttrInfo.OrigCallReturnPc =
1440         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_return_pc), 0);
1441     AttrInfo.OrigCallPc =
1442         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_pc), 0);
1443   }
1444 
1445   // Reset the Offset to 0 as we will be working on the local copy of
1446   // the data.
1447   Offset = 0;
1448 
1449   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1450   Offset += getULEB128Size(Abbrev->getCode());
1451 
1452   // We are entering a subprogram. Get and propagate the PCOffset.
1453   if (Die->getTag() == dwarf::DW_TAG_subprogram)
1454     PCOffset = Info.AddrAdjust;
1455   AttrInfo.PCOffset = PCOffset;
1456 
1457   if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1458     Flags |= TF_InFunctionScope;
1459     if (!Info.InDebugMap && LLVM_LIKELY(!Update))
1460       Flags |= TF_SkipPC;
1461   } else if (Abbrev->getTag() == dwarf::DW_TAG_variable) {
1462     // Function-local globals could be in the debug map even when the function
1463     // is not, e.g., inlined functions.
1464     if ((Flags & TF_InFunctionScope) && Info.InDebugMap)
1465       Flags &= ~TF_SkipPC;
1466   }
1467 
1468   for (const auto &AttrSpec : Abbrev->attributes()) {
1469     if (LLVM_LIKELY(!Update) &&
1470         shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
1471                             Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
1472       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
1473                                 U.getFormParams());
1474       continue;
1475     }
1476 
1477     DWARFFormValue Val(AttrSpec.Form);
1478     uint64_t AttrSize = Offset;
1479     Val.extractValue(Data, &Offset, U.getFormParams(), &U);
1480     AttrSize = Offset - AttrSize;
1481 
1482     OutOffset += cloneAttribute(*Die, InputDIE, File, Unit, StringPool, Val,
1483                                 AttrSpec, AttrSize, AttrInfo, IsLittleEndian);
1484   }
1485 
1486   // Look for accelerator entries.
1487   uint16_t Tag = InputDIE.getTag();
1488   // FIXME: This is slightly wrong. An inline_subroutine without a
1489   // low_pc, but with AT_ranges might be interesting to get into the
1490   // accelerator tables too. For now stick with dsymutil's behavior.
1491   if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
1492       Tag != dwarf::DW_TAG_compile_unit &&
1493       getDIENames(InputDIE, AttrInfo, StringPool,
1494                   Tag != dwarf::DW_TAG_inlined_subroutine)) {
1495     if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
1496       Unit.addNameAccelerator(Die, AttrInfo.MangledName,
1497                               Tag == dwarf::DW_TAG_inlined_subroutine);
1498     if (AttrInfo.Name) {
1499       if (AttrInfo.NameWithoutTemplate)
1500         Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
1501                                 /* SkipPubSection */ true);
1502       Unit.addNameAccelerator(Die, AttrInfo.Name,
1503                               Tag == dwarf::DW_TAG_inlined_subroutine);
1504     }
1505     if (AttrInfo.Name && isObjCSelector(AttrInfo.Name.getString()))
1506       addObjCAccelerator(Unit, Die, AttrInfo.Name, StringPool,
1507                          /* SkipPubSection =*/true);
1508 
1509   } else if (Tag == dwarf::DW_TAG_namespace) {
1510     if (!AttrInfo.Name)
1511       AttrInfo.Name = StringPool.getEntry("(anonymous namespace)");
1512     Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
1513   } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
1514              getDIENames(InputDIE, AttrInfo, StringPool) && AttrInfo.Name &&
1515              AttrInfo.Name.getString()[0]) {
1516     uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, File);
1517     uint64_t RuntimeLang =
1518         dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class))
1519             .value_or(0);
1520     bool ObjCClassIsImplementation =
1521         (RuntimeLang == dwarf::DW_LANG_ObjC ||
1522          RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
1523         dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type))
1524             .value_or(0);
1525     Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
1526                             Hash);
1527   }
1528 
1529   // Determine whether there are any children that we want to keep.
1530   bool HasChildren = false;
1531   for (auto Child : InputDIE.children()) {
1532     unsigned Idx = U.getDIEIndex(Child);
1533     if (Unit.getInfo(Idx).Keep) {
1534       HasChildren = true;
1535       break;
1536     }
1537   }
1538 
1539   DIEAbbrev NewAbbrev = Die->generateAbbrev();
1540   if (HasChildren)
1541     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1542   // Assign a permanent abbrev number
1543   Linker.assignAbbrev(NewAbbrev);
1544   Die->setAbbrevNumber(NewAbbrev.getNumber());
1545 
1546   // Add the size of the abbreviation number to the output offset.
1547   OutOffset += getULEB128Size(Die->getAbbrevNumber());
1548 
1549   if (!HasChildren) {
1550     // Update our size.
1551     Die->setSize(OutOffset - Die->getOffset());
1552     return Die;
1553   }
1554 
1555   // Recursively clone children.
1556   for (auto Child : InputDIE.children()) {
1557     if (DIE *Clone = cloneDIE(Child, File, Unit, StringPool, PCOffset,
1558                               OutOffset, Flags, IsLittleEndian)) {
1559       Die->addChild(Clone);
1560       OutOffset = Clone->getOffset() + Clone->getSize();
1561     }
1562   }
1563 
1564   // Account for the end of children marker.
1565   OutOffset += sizeof(int8_t);
1566   // Update our size.
1567   Die->setSize(OutOffset - Die->getOffset());
1568   return Die;
1569 }
1570 
1571 /// Patch the input object file relevant debug_ranges entries
1572 /// and emit them in the output file. Update the relevant attributes
1573 /// to point at the new entries.
patchRangesForUnit(const CompileUnit & Unit,DWARFContext & OrigDwarf,const DWARFFile & File) const1574 void DWARFLinker::patchRangesForUnit(const CompileUnit &Unit,
1575                                      DWARFContext &OrigDwarf,
1576                                      const DWARFFile &File) const {
1577   DWARFDebugRangeList RangeList;
1578   const auto &FunctionRanges = Unit.getFunctionRanges();
1579   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
1580   DWARFDataExtractor RangeExtractor(OrigDwarf.getDWARFObj(),
1581                                     OrigDwarf.getDWARFObj().getRangesSection(),
1582                                     OrigDwarf.isLittleEndian(), AddressSize);
1583   Optional<std::pair<AddressRange, int64_t>> CurrRange;
1584   DWARFUnit &OrigUnit = Unit.getOrigUnit();
1585   auto OrigUnitDie = OrigUnit.getUnitDIE(false);
1586   uint64_t OrigLowPc =
1587       dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc), -1ULL);
1588   // Ranges addresses are based on the unit's low_pc. Compute the
1589   // offset we need to apply to adapt to the new unit's low_pc.
1590   int64_t UnitPcOffset = 0;
1591   if (OrigLowPc != -1ULL)
1592     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
1593 
1594   for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
1595     uint64_t Offset = RangeAttribute.get();
1596     RangeAttribute.set(TheDwarfEmitter->getRangesSectionSize());
1597     if (Error E = RangeList.extract(RangeExtractor, &Offset)) {
1598       llvm::consumeError(std::move(E));
1599       reportWarning("invalid range list ignored.", File);
1600       RangeList.clear();
1601     }
1602     const auto &Entries = RangeList.getEntries();
1603     if (!Entries.empty()) {
1604       const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
1605 
1606       if (!CurrRange ||
1607           !CurrRange->first.contains(First.StartAddress + OrigLowPc)) {
1608         CurrRange = FunctionRanges.getRangeValueThatContains(
1609             First.StartAddress + OrigLowPc);
1610         if (!CurrRange) {
1611           reportWarning("no mapping for range.", File);
1612           continue;
1613         }
1614       }
1615     }
1616 
1617     TheDwarfEmitter->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange,
1618                                        Entries, AddressSize);
1619   }
1620 }
1621 
1622 /// Generate the debug_aranges entries for \p Unit and if the
1623 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
1624 /// contribution for this attribute.
1625 /// FIXME: this could actually be done right in patchRangesForUnit,
1626 /// but for the sake of initial bit-for-bit compatibility with legacy
1627 /// dsymutil, we have to do it in a delayed pass.
generateUnitRanges(CompileUnit & Unit) const1628 void DWARFLinker::generateUnitRanges(CompileUnit &Unit) const {
1629   auto Attr = Unit.getUnitRangesAttribute();
1630   if (Attr)
1631     Attr->set(TheDwarfEmitter->getRangesSectionSize());
1632   TheDwarfEmitter->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
1633 }
1634 
1635 /// Insert the new line info sequence \p Seq into the current
1636 /// set of already linked line info \p Rows.
insertLineSequence(std::vector<DWARFDebugLine::Row> & Seq,std::vector<DWARFDebugLine::Row> & Rows)1637 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
1638                                std::vector<DWARFDebugLine::Row> &Rows) {
1639   if (Seq.empty())
1640     return;
1641 
1642   if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
1643     llvm::append_range(Rows, Seq);
1644     Seq.clear();
1645     return;
1646   }
1647 
1648   object::SectionedAddress Front = Seq.front().Address;
1649   auto InsertPoint = partition_point(
1650       Rows, [=](const DWARFDebugLine::Row &O) { return O.Address < Front; });
1651 
1652   // FIXME: this only removes the unneeded end_sequence if the
1653   // sequences have been inserted in order. Using a global sort like
1654   // described in patchLineTableForUnit() and delaying the end_sequene
1655   // elimination to emitLineTableForUnit() we can get rid of all of them.
1656   if (InsertPoint != Rows.end() && InsertPoint->Address == Front &&
1657       InsertPoint->EndSequence) {
1658     *InsertPoint = Seq.front();
1659     Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
1660   } else {
1661     Rows.insert(InsertPoint, Seq.begin(), Seq.end());
1662   }
1663 
1664   Seq.clear();
1665 }
1666 
patchStmtList(DIE & Die,DIEInteger Offset)1667 static void patchStmtList(DIE &Die, DIEInteger Offset) {
1668   for (auto &V : Die.values())
1669     if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1670       V = DIEValue(V.getAttribute(), V.getForm(), Offset);
1671       return;
1672     }
1673 
1674   llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
1675 }
1676 
1677 /// Extract the line table for \p Unit from \p OrigDwarf, and
1678 /// recreate a relocated version of these for the address ranges that
1679 /// are present in the binary.
patchLineTableForUnit(CompileUnit & Unit,DWARFContext & OrigDwarf,const DWARFFile & File)1680 void DWARFLinker::patchLineTableForUnit(CompileUnit &Unit,
1681                                         DWARFContext &OrigDwarf,
1682                                         const DWARFFile &File) {
1683   DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
1684   auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
1685   if (!StmtList)
1686     return;
1687 
1688   // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
1689   if (auto *OutputDIE = Unit.getOutputUnitDIE())
1690     patchStmtList(*OutputDIE,
1691                   DIEInteger(TheDwarfEmitter->getLineSectionSize()));
1692 
1693   RangesTy &Ranges = File.Addresses->getValidAddressRanges();
1694 
1695   // Parse the original line info for the unit.
1696   DWARFDebugLine::LineTable LineTable;
1697   uint64_t StmtOffset = *StmtList;
1698   DWARFDataExtractor LineExtractor(
1699       OrigDwarf.getDWARFObj(), OrigDwarf.getDWARFObj().getLineSection(),
1700       OrigDwarf.isLittleEndian(), Unit.getOrigUnit().getAddressByteSize());
1701   if (needToTranslateStrings())
1702     return TheDwarfEmitter->translateLineTable(LineExtractor, StmtOffset);
1703 
1704   if (Error Err =
1705           LineTable.parse(LineExtractor, &StmtOffset, OrigDwarf,
1706                           &Unit.getOrigUnit(), OrigDwarf.getWarningHandler()))
1707     OrigDwarf.getWarningHandler()(std::move(Err));
1708 
1709   // This vector is the output line table.
1710   std::vector<DWARFDebugLine::Row> NewRows;
1711   NewRows.reserve(LineTable.Rows.size());
1712 
1713   // Current sequence of rows being extracted, before being inserted
1714   // in NewRows.
1715   std::vector<DWARFDebugLine::Row> Seq;
1716   const auto &FunctionRanges = Unit.getFunctionRanges();
1717   Optional<std::pair<AddressRange, int64_t>> CurrRange;
1718 
1719   // FIXME: This logic is meant to generate exactly the same output as
1720   // Darwin's classic dsymutil. There is a nicer way to implement this
1721   // by simply putting all the relocated line info in NewRows and simply
1722   // sorting NewRows before passing it to emitLineTableForUnit. This
1723   // should be correct as sequences for a function should stay
1724   // together in the sorted output. There are a few corner cases that
1725   // look suspicious though, and that required to implement the logic
1726   // this way. Revisit that once initial validation is finished.
1727 
1728   // Iterate over the object file line info and extract the sequences
1729   // that correspond to linked functions.
1730   for (auto &Row : LineTable.Rows) {
1731     // Check whether we stepped out of the range. The range is
1732     // half-open, but consider accept the end address of the range if
1733     // it is marked as end_sequence in the input (because in that
1734     // case, the relocation offset is accurate and that entry won't
1735     // serve as the start of another function).
1736     if (!CurrRange || !CurrRange->first.contains(Row.Address.Address) ||
1737         (Row.Address.Address == CurrRange->first.end() && !Row.EndSequence)) {
1738       // We just stepped out of a known range. Insert a end_sequence
1739       // corresponding to the end of the range.
1740       uint64_t StopAddress =
1741           CurrRange ? CurrRange->first.end() + CurrRange->second : -1ULL;
1742       CurrRange = FunctionRanges.getRangeValueThatContains(Row.Address.Address);
1743       if (!CurrRange) {
1744         if (StopAddress != -1ULL) {
1745           // Try harder by looking in the Address ranges map.
1746           // There are corner cases where this finds a
1747           // valid entry. It's unclear if this is right or wrong, but
1748           // for now do as dsymutil.
1749           // FIXME: Understand exactly what cases this addresses and
1750           // potentially remove it along with the Ranges map.
1751           if (Optional<std::pair<AddressRange, int64_t>> Range =
1752                   Ranges.getRangeValueThatContains(Row.Address.Address))
1753             StopAddress = Row.Address.Address + (*Range).second;
1754         }
1755       }
1756       if (StopAddress != -1ULL && !Seq.empty()) {
1757         // Insert end sequence row with the computed end address, but
1758         // the same line as the previous one.
1759         auto NextLine = Seq.back();
1760         NextLine.Address.Address = StopAddress;
1761         NextLine.EndSequence = 1;
1762         NextLine.PrologueEnd = 0;
1763         NextLine.BasicBlock = 0;
1764         NextLine.EpilogueBegin = 0;
1765         Seq.push_back(NextLine);
1766         insertLineSequence(Seq, NewRows);
1767       }
1768 
1769       if (!CurrRange)
1770         continue;
1771     }
1772 
1773     // Ignore empty sequences.
1774     if (Row.EndSequence && Seq.empty())
1775       continue;
1776 
1777     // Relocate row address and add it to the current sequence.
1778     Row.Address.Address += CurrRange->second;
1779     Seq.emplace_back(Row);
1780 
1781     if (Row.EndSequence)
1782       insertLineSequence(Seq, NewRows);
1783   }
1784 
1785   // Finished extracting, now emit the line tables.
1786   // FIXME: LLVM hard-codes its prologue values. We just copy the
1787   // prologue over and that works because we act as both producer and
1788   // consumer. It would be nicer to have a real configurable line
1789   // table emitter.
1790   if (LineTable.Prologue.getVersion() < 2 ||
1791       LineTable.Prologue.getVersion() > 5 ||
1792       LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
1793       LineTable.Prologue.OpcodeBase > 13)
1794     reportWarning("line table parameters mismatch. Cannot emit.", File);
1795   else {
1796     uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
1797     // DWARF v5 has an extra 2 bytes of information before the header_length
1798     // field.
1799     if (LineTable.Prologue.getVersion() == 5)
1800       PrologueEnd += 2;
1801     StringRef LineData = OrigDwarf.getDWARFObj().getLineSection().Data;
1802     MCDwarfLineTableParams Params;
1803     Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
1804     Params.DWARF2LineBase = LineTable.Prologue.LineBase;
1805     Params.DWARF2LineRange = LineTable.Prologue.LineRange;
1806     TheDwarfEmitter->emitLineTableForUnit(
1807         Params, LineData.slice(*StmtList + 4, PrologueEnd),
1808         LineTable.Prologue.MinInstLength, NewRows,
1809         Unit.getOrigUnit().getAddressByteSize());
1810   }
1811 }
1812 
emitAcceleratorEntriesForUnit(CompileUnit & Unit)1813 void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
1814   switch (Options.TheAccelTableKind) {
1815   case DwarfLinkerAccelTableKind::None:
1816     // Nothing to do.
1817     break;
1818   case DwarfLinkerAccelTableKind::Apple:
1819     emitAppleAcceleratorEntriesForUnit(Unit);
1820     break;
1821   case DwarfLinkerAccelTableKind::Dwarf:
1822     emitDwarfAcceleratorEntriesForUnit(Unit);
1823     break;
1824   case DwarfLinkerAccelTableKind::Pub:
1825     emitPubAcceleratorEntriesForUnit(Unit);
1826     break;
1827   case DwarfLinkerAccelTableKind::Default:
1828     llvm_unreachable("The default must be updated to a concrete value.");
1829     break;
1830   }
1831 }
1832 
emitAppleAcceleratorEntriesForUnit(CompileUnit & Unit)1833 void DWARFLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit &Unit) {
1834   // Add namespaces.
1835   for (const auto &Namespace : Unit.getNamespaces())
1836     AppleNamespaces.addName(Namespace.Name,
1837                             Namespace.Die->getOffset() + Unit.getStartOffset());
1838 
1839   /// Add names.
1840   for (const auto &Pubname : Unit.getPubnames())
1841     AppleNames.addName(Pubname.Name,
1842                        Pubname.Die->getOffset() + Unit.getStartOffset());
1843 
1844   /// Add types.
1845   for (const auto &Pubtype : Unit.getPubtypes())
1846     AppleTypes.addName(
1847         Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
1848         Pubtype.Die->getTag(),
1849         Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
1850                                         : 0,
1851         Pubtype.QualifiedNameHash);
1852 
1853   /// Add ObjC names.
1854   for (const auto &ObjC : Unit.getObjC())
1855     AppleObjc.addName(ObjC.Name, ObjC.Die->getOffset() + Unit.getStartOffset());
1856 }
1857 
emitDwarfAcceleratorEntriesForUnit(CompileUnit & Unit)1858 void DWARFLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit &Unit) {
1859   for (const auto &Namespace : Unit.getNamespaces())
1860     DebugNames.addName(Namespace.Name, Namespace.Die->getOffset(),
1861                        Namespace.Die->getTag(), Unit.getUniqueID());
1862   for (const auto &Pubname : Unit.getPubnames())
1863     DebugNames.addName(Pubname.Name, Pubname.Die->getOffset(),
1864                        Pubname.Die->getTag(), Unit.getUniqueID());
1865   for (const auto &Pubtype : Unit.getPubtypes())
1866     DebugNames.addName(Pubtype.Name, Pubtype.Die->getOffset(),
1867                        Pubtype.Die->getTag(), Unit.getUniqueID());
1868 }
1869 
emitPubAcceleratorEntriesForUnit(CompileUnit & Unit)1870 void DWARFLinker::emitPubAcceleratorEntriesForUnit(CompileUnit &Unit) {
1871   TheDwarfEmitter->emitPubNamesForUnit(Unit);
1872   TheDwarfEmitter->emitPubTypesForUnit(Unit);
1873 }
1874 
1875 /// Read the frame info stored in the object, and emit the
1876 /// patched frame descriptions for the resulting file.
1877 ///
1878 /// This is actually pretty easy as the data of the CIEs and FDEs can
1879 /// be considered as black boxes and moved as is. The only thing to do
1880 /// is to patch the addresses in the headers.
patchFrameInfoForObject(const DWARFFile & File,RangesTy & Ranges,DWARFContext & OrigDwarf,unsigned AddrSize)1881 void DWARFLinker::patchFrameInfoForObject(const DWARFFile &File,
1882                                           RangesTy &Ranges,
1883                                           DWARFContext &OrigDwarf,
1884                                           unsigned AddrSize) {
1885   StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
1886   if (FrameData.empty())
1887     return;
1888 
1889   DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
1890   uint64_t InputOffset = 0;
1891 
1892   // Store the data of the CIEs defined in this object, keyed by their
1893   // offsets.
1894   DenseMap<uint64_t, StringRef> LocalCIES;
1895 
1896   while (Data.isValidOffset(InputOffset)) {
1897     uint64_t EntryOffset = InputOffset;
1898     uint32_t InitialLength = Data.getU32(&InputOffset);
1899     if (InitialLength == 0xFFFFFFFF)
1900       return reportWarning("Dwarf64 bits no supported", File);
1901 
1902     uint32_t CIEId = Data.getU32(&InputOffset);
1903     if (CIEId == 0xFFFFFFFF) {
1904       // This is a CIE, store it.
1905       StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
1906       LocalCIES[EntryOffset] = CIEData;
1907       // The -4 is to account for the CIEId we just read.
1908       InputOffset += InitialLength - 4;
1909       continue;
1910     }
1911 
1912     uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
1913 
1914     // Some compilers seem to emit frame info that doesn't start at
1915     // the function entry point, thus we can't just lookup the address
1916     // in the debug map. Use the AddressInfo's range map to see if the FDE
1917     // describes something that we can relocate.
1918     Optional<std::pair<AddressRange, int64_t>> Range =
1919         Ranges.getRangeValueThatContains(Loc);
1920     if (!Range) {
1921       // The +4 is to account for the size of the InitialLength field itself.
1922       InputOffset = EntryOffset + InitialLength + 4;
1923       continue;
1924     }
1925 
1926     // This is an FDE, and we have a mapping.
1927     // Have we already emitted a corresponding CIE?
1928     StringRef CIEData = LocalCIES[CIEId];
1929     if (CIEData.empty())
1930       return reportWarning("Inconsistent debug_frame content. Dropping.", File);
1931 
1932     // Look if we already emitted a CIE that corresponds to the
1933     // referenced one (the CIE data is the key of that lookup).
1934     auto IteratorInserted = EmittedCIEs.insert(
1935         std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
1936     // If there is no CIE yet for this ID, emit it.
1937     if (IteratorInserted.second) {
1938       LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
1939       IteratorInserted.first->getValue() = LastCIEOffset;
1940       TheDwarfEmitter->emitCIE(CIEData);
1941     }
1942 
1943     // Emit the FDE with updated address and CIE pointer.
1944     // (4 + AddrSize) is the size of the CIEId + initial_location
1945     // fields that will get reconstructed by emitFDE().
1946     unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
1947     TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), AddrSize,
1948                              Loc + Range->second,
1949                              FrameData.substr(InputOffset, FDERemainingBytes));
1950     InputOffset += FDERemainingBytes;
1951   }
1952 }
1953 
hashFullyQualifiedName(DWARFDie DIE,CompileUnit & U,const DWARFFile & File,int ChildRecurseDepth)1954 uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE,
1955                                                         CompileUnit &U,
1956                                                         const DWARFFile &File,
1957                                                         int ChildRecurseDepth) {
1958   const char *Name = nullptr;
1959   DWARFUnit *OrigUnit = &U.getOrigUnit();
1960   CompileUnit *CU = &U;
1961   Optional<DWARFFormValue> Ref;
1962 
1963   while (true) {
1964     if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
1965       Name = CurrentName;
1966 
1967     if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
1968         !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
1969       break;
1970 
1971     if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
1972       break;
1973 
1974     CompileUnit *RefCU;
1975     if (auto RefDIE =
1976             Linker.resolveDIEReference(File, CompileUnits, *Ref, DIE, RefCU)) {
1977       CU = RefCU;
1978       OrigUnit = &RefCU->getOrigUnit();
1979       DIE = RefDIE;
1980     }
1981   }
1982 
1983   unsigned Idx = OrigUnit->getDIEIndex(DIE);
1984   if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
1985     Name = "(anonymous namespace)";
1986 
1987   if (CU->getInfo(Idx).ParentIdx == 0 ||
1988       // FIXME: dsymutil-classic compatibility. Ignore modules.
1989       CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
1990           dwarf::DW_TAG_module)
1991     return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
1992 
1993   DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
1994   return djbHash(
1995       (Name ? Name : ""),
1996       djbHash((Name ? "::" : ""),
1997               hashFullyQualifiedName(Die, *CU, File, ++ChildRecurseDepth)));
1998 }
1999 
getDwoId(const DWARFDie & CUDie,const DWARFUnit & Unit)2000 static uint64_t getDwoId(const DWARFDie &CUDie, const DWARFUnit &Unit) {
2001   auto DwoId = dwarf::toUnsigned(
2002       CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
2003   if (DwoId)
2004     return *DwoId;
2005   return 0;
2006 }
2007 
remapPath(StringRef Path,const objectPrefixMap & ObjectPrefixMap)2008 static std::string remapPath(StringRef Path,
2009                              const objectPrefixMap &ObjectPrefixMap) {
2010   if (ObjectPrefixMap.empty())
2011     return Path.str();
2012 
2013   SmallString<256> p = Path;
2014   for (const auto &Entry : ObjectPrefixMap)
2015     if (llvm::sys::path::replace_path_prefix(p, Entry.first, Entry.second))
2016       break;
2017   return p.str().str();
2018 }
2019 
registerModuleReference(DWARFDie CUDie,const DWARFUnit & Unit,const DWARFFile & File,OffsetsStringPool & StringPool,DeclContextTree & ODRContexts,uint64_t ModulesEndOffset,unsigned & UnitID,bool IsLittleEndian,unsigned Indent,bool Quiet)2020 bool DWARFLinker::registerModuleReference(DWARFDie CUDie, const DWARFUnit &Unit,
2021                                           const DWARFFile &File,
2022                                           OffsetsStringPool &StringPool,
2023                                           DeclContextTree &ODRContexts,
2024                                           uint64_t ModulesEndOffset,
2025                                           unsigned &UnitID, bool IsLittleEndian,
2026                                           unsigned Indent, bool Quiet) {
2027   std::string PCMfile = dwarf::toString(
2028       CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
2029   if (PCMfile.empty())
2030     return false;
2031   if (Options.ObjectPrefixMap)
2032     PCMfile = remapPath(PCMfile, *Options.ObjectPrefixMap);
2033 
2034   // Clang module DWARF skeleton CUs abuse this for the path to the module.
2035   uint64_t DwoId = getDwoId(CUDie, Unit);
2036 
2037   std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
2038   if (Name.empty()) {
2039     if (!Quiet)
2040       reportWarning("Anonymous module skeleton CU for " + PCMfile, File);
2041     return true;
2042   }
2043 
2044   if (!Quiet && Options.Verbose) {
2045     outs().indent(Indent);
2046     outs() << "Found clang module reference " << PCMfile;
2047   }
2048 
2049   auto Cached = ClangModules.find(PCMfile);
2050   if (Cached != ClangModules.end()) {
2051     // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2052     // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2053     // ASTFileSignatures will change randomly when a module is rebuilt.
2054     if (!Quiet && Options.Verbose && (Cached->second != DwoId))
2055       reportWarning(Twine("hash mismatch: this object file was built against a "
2056                           "different version of the module ") +
2057                         PCMfile,
2058                     File);
2059     if (!Quiet && Options.Verbose)
2060       outs() << " [cached].\n";
2061     return true;
2062   }
2063   if (!Quiet && Options.Verbose)
2064     outs() << " ...\n";
2065 
2066   // Cyclic dependencies are disallowed by Clang, but we still
2067   // shouldn't run into an infinite loop, so mark it as processed now.
2068   ClangModules.insert({PCMfile, DwoId});
2069 
2070   if (Error E = loadClangModule(CUDie, PCMfile, Name, DwoId, File, StringPool,
2071                                 ODRContexts, ModulesEndOffset, UnitID,
2072                                 IsLittleEndian, Indent + 2, Quiet)) {
2073     consumeError(std::move(E));
2074     return false;
2075   }
2076   return true;
2077 }
2078 
loadClangModule(DWARFDie CUDie,StringRef Filename,StringRef ModuleName,uint64_t DwoId,const DWARFFile & File,OffsetsStringPool & StringPool,DeclContextTree & ODRContexts,uint64_t ModulesEndOffset,unsigned & UnitID,bool IsLittleEndian,unsigned Indent,bool Quiet)2079 Error DWARFLinker::loadClangModule(
2080     DWARFDie CUDie, StringRef Filename, StringRef ModuleName, uint64_t DwoId,
2081     const DWARFFile &File, OffsetsStringPool &StringPool,
2082     DeclContextTree &ODRContexts, uint64_t ModulesEndOffset, unsigned &UnitID,
2083     bool IsLittleEndian, unsigned Indent, bool Quiet) {
2084   /// Using a SmallString<0> because loadClangModule() is recursive.
2085   SmallString<0> Path(Options.PrependPath);
2086   if (sys::path::is_relative(Filename))
2087     resolveRelativeObjectPath(Path, CUDie);
2088   sys::path::append(Path, Filename);
2089   // Don't use the cached binary holder because we have no thread-safety
2090   // guarantee and the lifetime is limited.
2091 
2092   if (Options.ObjFileLoader == nullptr)
2093     return Error::success();
2094 
2095   auto ErrOrObj = Options.ObjFileLoader(File.FileName, Path);
2096   if (!ErrOrObj)
2097     return Error::success();
2098 
2099   std::unique_ptr<CompileUnit> Unit;
2100 
2101   for (const auto &CU : ErrOrObj->Dwarf->compile_units()) {
2102     updateDwarfVersion(CU->getVersion());
2103     // Recursively get all modules imported by this one.
2104     auto CUDie = CU->getUnitDIE(false);
2105     if (!CUDie)
2106       continue;
2107     if (!registerModuleReference(CUDie, *CU, File, StringPool, ODRContexts,
2108                                  ModulesEndOffset, UnitID, IsLittleEndian,
2109                                  Indent, Quiet)) {
2110       if (Unit) {
2111         std::string Err =
2112             (Filename +
2113              ": Clang modules are expected to have exactly 1 compile unit.\n")
2114                 .str();
2115         reportError(Err, File);
2116         return make_error<StringError>(Err, inconvertibleErrorCode());
2117       }
2118       // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2119       // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2120       // ASTFileSignatures will change randomly when a module is rebuilt.
2121       uint64_t PCMDwoId = getDwoId(CUDie, *CU);
2122       if (PCMDwoId != DwoId) {
2123         if (!Quiet && Options.Verbose)
2124           reportWarning(
2125               Twine("hash mismatch: this object file was built against a "
2126                     "different version of the module ") +
2127                   Filename,
2128               File);
2129         // Update the cache entry with the DwoId of the module loaded from disk.
2130         ClangModules[Filename] = PCMDwoId;
2131       }
2132 
2133       // Add this module.
2134       Unit = std::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
2135                                            ModuleName);
2136       analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), ODRContexts,
2137                          ModulesEndOffset, Options.ParseableSwiftInterfaces,
2138                          [&](const Twine &Warning, const DWARFDie &DIE) {
2139                            reportWarning(Warning, File, &DIE);
2140                          });
2141       // Keep everything.
2142       Unit->markEverythingAsKept();
2143     }
2144   }
2145   assert(Unit && "CompileUnit is not set!");
2146   if (!Unit->getOrigUnit().getUnitDIE().hasChildren())
2147     return Error::success();
2148   if (!Quiet && Options.Verbose) {
2149     outs().indent(Indent);
2150     outs() << "cloning .debug_info from " << Filename << "\n";
2151   }
2152 
2153   UnitListTy CompileUnits;
2154   CompileUnits.push_back(std::move(Unit));
2155   assert(TheDwarfEmitter);
2156   DIECloner(*this, TheDwarfEmitter, *ErrOrObj, DIEAlloc, CompileUnits,
2157             Options.Update)
2158       .cloneAllCompileUnits(*(ErrOrObj->Dwarf), File, StringPool,
2159                             IsLittleEndian);
2160   return Error::success();
2161 }
2162 
cloneAllCompileUnits(DWARFContext & DwarfContext,const DWARFFile & File,OffsetsStringPool & StringPool,bool IsLittleEndian)2163 uint64_t DWARFLinker::DIECloner::cloneAllCompileUnits(
2164     DWARFContext &DwarfContext, const DWARFFile &File,
2165     OffsetsStringPool &StringPool, bool IsLittleEndian) {
2166   uint64_t OutputDebugInfoSize =
2167       Linker.Options.NoOutput ? 0 : Emitter->getDebugInfoSectionSize();
2168   const uint64_t StartOutputDebugInfoSize = OutputDebugInfoSize;
2169 
2170   for (auto &CurrentUnit : CompileUnits) {
2171     const uint16_t DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2172     const uint32_t UnitHeaderSize = DwarfVersion >= 5 ? 12 : 11;
2173     auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
2174     CurrentUnit->setStartOffset(OutputDebugInfoSize);
2175     if (!InputDIE) {
2176       OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2177       continue;
2178     }
2179     if (CurrentUnit->getInfo(0).Keep) {
2180       // Clone the InputDIE into your Unit DIE in our compile unit since it
2181       // already has a DIE inside of it.
2182       CurrentUnit->createOutputDIE();
2183       cloneDIE(InputDIE, File, *CurrentUnit, StringPool, 0 /* PC offset */,
2184                UnitHeaderSize, 0, IsLittleEndian,
2185                CurrentUnit->getOutputUnitDIE());
2186     }
2187 
2188     OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2189 
2190     if (!Linker.Options.NoOutput) {
2191       assert(Emitter);
2192 
2193       if (LLVM_LIKELY(!Linker.Options.Update) ||
2194           Linker.needToTranslateStrings())
2195         Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext, File);
2196 
2197       Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2198 
2199       if (LLVM_UNLIKELY(Linker.Options.Update))
2200         continue;
2201 
2202       Linker.patchRangesForUnit(*CurrentUnit, DwarfContext, File);
2203       auto ProcessExpr = [&](StringRef Bytes,
2204                              SmallVectorImpl<uint8_t> &Buffer) {
2205         DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2206         DataExtractor Data(Bytes, IsLittleEndian,
2207                            OrigUnit.getAddressByteSize());
2208         cloneExpression(Data,
2209                         DWARFExpression(Data, OrigUnit.getAddressByteSize(),
2210                                         OrigUnit.getFormParams().Format),
2211                         File, *CurrentUnit, Buffer);
2212       };
2213       Emitter->emitLocationsForUnit(*CurrentUnit, DwarfContext, ProcessExpr);
2214     }
2215   }
2216 
2217   if (!Linker.Options.NoOutput) {
2218     assert(Emitter);
2219     // Emit all the compile unit's debug information.
2220     for (auto &CurrentUnit : CompileUnits) {
2221       if (LLVM_LIKELY(!Linker.Options.Update))
2222         Linker.generateUnitRanges(*CurrentUnit);
2223 
2224       CurrentUnit->fixupForwardReferences();
2225 
2226       if (!CurrentUnit->getOutputUnitDIE())
2227         continue;
2228 
2229       unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2230 
2231       assert(Emitter->getDebugInfoSectionSize() ==
2232              CurrentUnit->getStartOffset());
2233       Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion);
2234       Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
2235       assert(Emitter->getDebugInfoSectionSize() ==
2236              CurrentUnit->computeNextUnitOffset(DwarfVersion));
2237     }
2238   }
2239 
2240   return OutputDebugInfoSize - StartOutputDebugInfoSize;
2241 }
2242 
updateAccelKind(DWARFContext & Dwarf)2243 void DWARFLinker::updateAccelKind(DWARFContext &Dwarf) {
2244   if (Options.TheAccelTableKind != DwarfLinkerAccelTableKind::Default)
2245     return;
2246 
2247   auto &DwarfObj = Dwarf.getDWARFObj();
2248 
2249   if (!AtLeastOneDwarfAccelTable &&
2250       (!DwarfObj.getAppleNamesSection().Data.empty() ||
2251        !DwarfObj.getAppleTypesSection().Data.empty() ||
2252        !DwarfObj.getAppleNamespacesSection().Data.empty() ||
2253        !DwarfObj.getAppleObjCSection().Data.empty())) {
2254     AtLeastOneAppleAccelTable = true;
2255   }
2256 
2257   if (!AtLeastOneDwarfAccelTable && !DwarfObj.getNamesSection().Data.empty()) {
2258     AtLeastOneDwarfAccelTable = true;
2259   }
2260 }
2261 
emitPaperTrailWarnings(const DWARFFile & File,OffsetsStringPool & StringPool)2262 bool DWARFLinker::emitPaperTrailWarnings(const DWARFFile &File,
2263                                          OffsetsStringPool &StringPool) {
2264 
2265   if (File.Warnings.empty())
2266     return false;
2267 
2268   DIE *CUDie = DIE::get(DIEAlloc, dwarf::DW_TAG_compile_unit);
2269   CUDie->setOffset(11);
2270   StringRef Producer;
2271   StringRef WarningHeader;
2272 
2273   switch (DwarfLinkerClientID) {
2274   case DwarfLinkerClient::Dsymutil:
2275     Producer = StringPool.internString("dsymutil");
2276     WarningHeader = "dsymutil_warning";
2277     break;
2278 
2279   default:
2280     Producer = StringPool.internString("dwarfopt");
2281     WarningHeader = "dwarfopt_warning";
2282     break;
2283   }
2284 
2285   StringRef FileName = StringPool.internString(File.FileName);
2286   CUDie->addValue(DIEAlloc, dwarf::DW_AT_producer, dwarf::DW_FORM_strp,
2287                   DIEInteger(StringPool.getStringOffset(Producer)));
2288   DIEBlock *String = new (DIEAlloc) DIEBlock();
2289   DIEBlocks.push_back(String);
2290   for (auto &C : FileName)
2291     String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2292                      DIEInteger(C));
2293   String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2294                    DIEInteger(0));
2295 
2296   CUDie->addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_string, String);
2297   for (const auto &Warning : File.Warnings) {
2298     DIE &ConstDie = CUDie->addChild(DIE::get(DIEAlloc, dwarf::DW_TAG_constant));
2299     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp,
2300                       DIEInteger(StringPool.getStringOffset(WarningHeader)));
2301     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag,
2302                       DIEInteger(1));
2303     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_strp,
2304                       DIEInteger(StringPool.getStringOffset(Warning)));
2305   }
2306   unsigned Size = 4 /* FORM_strp */ + FileName.size() + 1 +
2307                   File.Warnings.size() * (4 + 1 + 4) + 1 /* End of children */;
2308   DIEAbbrev Abbrev = CUDie->generateAbbrev();
2309   assignAbbrev(Abbrev);
2310   CUDie->setAbbrevNumber(Abbrev.getNumber());
2311   Size += getULEB128Size(Abbrev.getNumber());
2312   // Abbreviation ordering needed for classic compatibility.
2313   for (auto &Child : CUDie->children()) {
2314     Abbrev = Child.generateAbbrev();
2315     assignAbbrev(Abbrev);
2316     Child.setAbbrevNumber(Abbrev.getNumber());
2317     Size += getULEB128Size(Abbrev.getNumber());
2318   }
2319   CUDie->setSize(Size);
2320   TheDwarfEmitter->emitPaperTrailWarningsDie(*CUDie);
2321 
2322   return true;
2323 }
2324 
copyInvariantDebugSection(DWARFContext & Dwarf)2325 void DWARFLinker::copyInvariantDebugSection(DWARFContext &Dwarf) {
2326   if (!needToTranslateStrings())
2327     TheDwarfEmitter->emitSectionContents(
2328         Dwarf.getDWARFObj().getLineSection().Data, "debug_line");
2329   TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getLocSection().Data,
2330                                        "debug_loc");
2331   TheDwarfEmitter->emitSectionContents(
2332       Dwarf.getDWARFObj().getRangesSection().Data, "debug_ranges");
2333   TheDwarfEmitter->emitSectionContents(
2334       Dwarf.getDWARFObj().getFrameSection().Data, "debug_frame");
2335   TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getArangesSection(),
2336                                        "debug_aranges");
2337 }
2338 
addObjectFile(DWARFFile & File)2339 void DWARFLinker::addObjectFile(DWARFFile &File) {
2340   ObjectContexts.emplace_back(LinkContext(File));
2341 
2342   if (ObjectContexts.back().File.Dwarf)
2343     updateAccelKind(*ObjectContexts.back().File.Dwarf);
2344 }
2345 
link()2346 Error DWARFLinker::link() {
2347   assert(Options.NoOutput || TheDwarfEmitter);
2348 
2349   // A unique ID that identifies each compile unit.
2350   unsigned UnitID = 0;
2351 
2352   // First populate the data structure we need for each iteration of the
2353   // parallel loop.
2354   unsigned NumObjects = ObjectContexts.size();
2355 
2356   // This Dwarf string pool which is used for emission. It must be used
2357   // serially as the order of calling getStringOffset matters for
2358   // reproducibility.
2359   OffsetsStringPool OffsetsStringPool(StringsTranslator, true);
2360 
2361   // ODR Contexts for the optimize.
2362   DeclContextTree ODRContexts;
2363 
2364   // If we haven't decided on an accelerator table kind yet, we base ourselves
2365   // on the DWARF we have seen so far. At this point we haven't pulled in debug
2366   // information from modules yet, so it is technically possible that they
2367   // would affect the decision. However, as they're built with the same
2368   // compiler and flags, it is safe to assume that they will follow the
2369   // decision made here.
2370   if (Options.TheAccelTableKind == DwarfLinkerAccelTableKind::Default) {
2371     if (AtLeastOneDwarfAccelTable && !AtLeastOneAppleAccelTable)
2372       Options.TheAccelTableKind = DwarfLinkerAccelTableKind::Dwarf;
2373     else
2374       Options.TheAccelTableKind = DwarfLinkerAccelTableKind::Apple;
2375   }
2376 
2377   for (LinkContext &OptContext : ObjectContexts) {
2378     if (Options.Verbose) {
2379       if (DwarfLinkerClientID == DwarfLinkerClient::Dsymutil)
2380         outs() << "DEBUG MAP OBJECT: " << OptContext.File.FileName << "\n";
2381       else
2382         outs() << "OBJECT FILE: " << OptContext.File.FileName << "\n";
2383     }
2384 
2385     if (emitPaperTrailWarnings(OptContext.File, OffsetsStringPool))
2386       continue;
2387 
2388     if (!OptContext.File.Dwarf)
2389       continue;
2390 
2391     if (Options.VerifyInputDWARF)
2392       verify(OptContext.File);
2393 
2394     // Look for relocations that correspond to address map entries.
2395 
2396     // there was findvalidrelocations previously ... probably we need to gather
2397     // info here
2398     if (LLVM_LIKELY(!Options.Update) &&
2399         !OptContext.File.Addresses->hasValidRelocs()) {
2400       if (Options.Verbose)
2401         outs() << "No valid relocations found. Skipping.\n";
2402 
2403       // Set "Skip" flag as a signal to other loops that we should not
2404       // process this iteration.
2405       OptContext.Skip = true;
2406       continue;
2407     }
2408 
2409     // Setup access to the debug info.
2410     if (!OptContext.File.Dwarf)
2411       continue;
2412 
2413     // Check whether type units are presented.
2414     if (!OptContext.File.Dwarf->types_section_units().empty()) {
2415       reportWarning("type units are not currently supported: file will "
2416                     "be skipped",
2417                     OptContext.File);
2418       OptContext.Skip = true;
2419       continue;
2420     }
2421 
2422     // Check for unsupported sections. Following sections can be referenced
2423     // from .debug_info section. Current DWARFLinker implementation does not
2424     // support or update references to these tables. Thus we report warning
2425     // and skip corresponding object file.
2426     if (!OptContext.File.Dwarf->getDWARFObj()
2427              .getRnglistsSection()
2428              .Data.empty()) {
2429       reportWarning("'.debug_rnglists' is not currently supported: file "
2430                     "will be skipped",
2431                     OptContext.File);
2432       OptContext.Skip = true;
2433       continue;
2434     }
2435 
2436     if (!OptContext.File.Dwarf->getDWARFObj()
2437              .getLoclistsSection()
2438              .Data.empty()) {
2439       reportWarning("'.debug_loclists' is not currently supported: file "
2440                     "will be skipped",
2441                     OptContext.File);
2442       OptContext.Skip = true;
2443       continue;
2444     }
2445 
2446     if (!OptContext.File.Dwarf->getDWARFObj().getMacroSection().Data.empty()) {
2447       reportWarning("'.debug_macro' is not currently supported: file "
2448                     "will be skipped",
2449                     OptContext.File);
2450       OptContext.Skip = true;
2451       continue;
2452     }
2453 
2454     if (OptContext.File.Dwarf->getDWARFObj().getMacinfoSection().size() > 1) {
2455       reportWarning("'.debug_macinfo' is not currently supported: file "
2456                     "will be skipped",
2457                     OptContext.File);
2458       OptContext.Skip = true;
2459       continue;
2460     }
2461 
2462     // In a first phase, just read in the debug info and load all clang modules.
2463     OptContext.CompileUnits.reserve(
2464         OptContext.File.Dwarf->getNumCompileUnits());
2465 
2466     for (const auto &CU : OptContext.File.Dwarf->compile_units()) {
2467       updateDwarfVersion(CU->getVersion());
2468       auto CUDie = CU->getUnitDIE(false);
2469       if (Options.Verbose) {
2470         outs() << "Input compilation unit:";
2471         DIDumpOptions DumpOpts;
2472         DumpOpts.ChildRecurseDepth = 0;
2473         DumpOpts.Verbose = Options.Verbose;
2474         CUDie.dump(outs(), 0, DumpOpts);
2475       }
2476       if (CUDie && !LLVM_UNLIKELY(Options.Update))
2477         registerModuleReference(CUDie, *CU, OptContext.File, OffsetsStringPool,
2478                                 ODRContexts, 0, UnitID,
2479                                 OptContext.File.Dwarf->isLittleEndian());
2480     }
2481   }
2482 
2483   // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
2484   if (MaxDwarfVersion == 0)
2485     MaxDwarfVersion = 3;
2486 
2487   // At this point we know how much data we have emitted. We use this value to
2488   // compare canonical DIE offsets in analyzeContextInfo to see if a definition
2489   // is already emitted, without being affected by canonical die offsets set
2490   // later. This prevents undeterminism when analyze and clone execute
2491   // concurrently, as clone set the canonical DIE offset and analyze reads it.
2492   const uint64_t ModulesEndOffset =
2493       Options.NoOutput ? 0 : TheDwarfEmitter->getDebugInfoSectionSize();
2494 
2495   // These variables manage the list of processed object files.
2496   // The mutex and condition variable are to ensure that this is thread safe.
2497   std::mutex ProcessedFilesMutex;
2498   std::condition_variable ProcessedFilesConditionVariable;
2499   BitVector ProcessedFiles(NumObjects, false);
2500 
2501   //  Analyzing the context info is particularly expensive so it is executed in
2502   //  parallel with emitting the previous compile unit.
2503   auto AnalyzeLambda = [&](size_t I) {
2504     auto &Context = ObjectContexts[I];
2505 
2506     if (Context.Skip || !Context.File.Dwarf)
2507       return;
2508 
2509     for (const auto &CU : Context.File.Dwarf->compile_units()) {
2510       updateDwarfVersion(CU->getVersion());
2511       // The !registerModuleReference() condition effectively skips
2512       // over fully resolved skeleton units. This second pass of
2513       // registerModuleReferences doesn't do any new work, but it
2514       // will collect top-level errors, which are suppressed. Module
2515       // warnings were already displayed in the first iteration.
2516       bool Quiet = true;
2517       auto CUDie = CU->getUnitDIE(false);
2518       if (!CUDie || LLVM_UNLIKELY(Options.Update) ||
2519           !registerModuleReference(CUDie, *CU, Context.File, OffsetsStringPool,
2520                                    ODRContexts, ModulesEndOffset, UnitID,
2521                                    Quiet)) {
2522         Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
2523             *CU, UnitID++, !Options.NoODR && !Options.Update, ""));
2524       }
2525     }
2526 
2527     // Now build the DIE parent links that we will use during the next phase.
2528     for (auto &CurrentUnit : Context.CompileUnits) {
2529       auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
2530       if (!CUDie)
2531         continue;
2532       analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
2533                          *CurrentUnit, &ODRContexts.getRoot(), ODRContexts,
2534                          ModulesEndOffset, Options.ParseableSwiftInterfaces,
2535                          [&](const Twine &Warning, const DWARFDie &DIE) {
2536                            reportWarning(Warning, Context.File, &DIE);
2537                          });
2538     }
2539   };
2540 
2541   // For each object file map how many bytes were emitted.
2542   StringMap<DebugInfoSize> SizeByObject;
2543 
2544   // And then the remaining work in serial again.
2545   // Note, although this loop runs in serial, it can run in parallel with
2546   // the analyzeContextInfo loop so long as we process files with indices >=
2547   // than those processed by analyzeContextInfo.
2548   auto CloneLambda = [&](size_t I) {
2549     auto &OptContext = ObjectContexts[I];
2550     if (OptContext.Skip || !OptContext.File.Dwarf)
2551       return;
2552 
2553     // Then mark all the DIEs that need to be present in the generated output
2554     // and collect some information about them.
2555     // Note that this loop can not be merged with the previous one because
2556     // cross-cu references require the ParentIdx to be setup for every CU in
2557     // the object file before calling this.
2558     if (LLVM_UNLIKELY(Options.Update)) {
2559       for (auto &CurrentUnit : OptContext.CompileUnits)
2560         CurrentUnit->markEverythingAsKept();
2561       copyInvariantDebugSection(*OptContext.File.Dwarf);
2562     } else {
2563       for (auto &CurrentUnit : OptContext.CompileUnits)
2564         lookForDIEsToKeep(*OptContext.File.Addresses,
2565                           OptContext.File.Addresses->getValidAddressRanges(),
2566                           OptContext.CompileUnits,
2567                           CurrentUnit->getOrigUnit().getUnitDIE(),
2568                           OptContext.File, *CurrentUnit, 0);
2569     }
2570 
2571     // The calls to applyValidRelocs inside cloneDIE will walk the reloc
2572     // array again (in the same way findValidRelocsInDebugInfo() did). We
2573     // need to reset the NextValidReloc index to the beginning.
2574     if (OptContext.File.Addresses->hasValidRelocs() ||
2575         LLVM_UNLIKELY(Options.Update)) {
2576       SizeByObject[OptContext.File.FileName].Input =
2577           getDebugInfoSize(*OptContext.File.Dwarf);
2578       SizeByObject[OptContext.File.FileName].Output =
2579           DIECloner(*this, TheDwarfEmitter, OptContext.File, DIEAlloc,
2580                     OptContext.CompileUnits, Options.Update)
2581               .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
2582                                     OffsetsStringPool,
2583                                     OptContext.File.Dwarf->isLittleEndian());
2584     }
2585     if (!Options.NoOutput && !OptContext.CompileUnits.empty() &&
2586         LLVM_LIKELY(!Options.Update))
2587       patchFrameInfoForObject(
2588           OptContext.File, OptContext.File.Addresses->getValidAddressRanges(),
2589           *OptContext.File.Dwarf,
2590           OptContext.CompileUnits[0]->getOrigUnit().getAddressByteSize());
2591 
2592     // Clean-up before starting working on the next object.
2593     cleanupAuxiliarryData(OptContext);
2594   };
2595 
2596   auto EmitLambda = [&]() {
2597     // Emit everything that's global.
2598     if (!Options.NoOutput) {
2599       TheDwarfEmitter->emitAbbrevs(Abbreviations, MaxDwarfVersion);
2600       TheDwarfEmitter->emitStrings(OffsetsStringPool);
2601       switch (Options.TheAccelTableKind) {
2602       case DwarfLinkerAccelTableKind::None:
2603         // Nothing to do.
2604         break;
2605       case DwarfLinkerAccelTableKind::Apple:
2606         TheDwarfEmitter->emitAppleNames(AppleNames);
2607         TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
2608         TheDwarfEmitter->emitAppleTypes(AppleTypes);
2609         TheDwarfEmitter->emitAppleObjc(AppleObjc);
2610         break;
2611       case DwarfLinkerAccelTableKind::Dwarf:
2612         TheDwarfEmitter->emitDebugNames(DebugNames);
2613         break;
2614       case DwarfLinkerAccelTableKind::Pub:
2615         // Already emitted by emitPubAcceleratorEntriesForUnit.
2616         break;
2617       case DwarfLinkerAccelTableKind::Default:
2618         llvm_unreachable("Default should have already been resolved.");
2619         break;
2620       }
2621     }
2622   };
2623 
2624   auto AnalyzeAll = [&]() {
2625     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2626       AnalyzeLambda(I);
2627 
2628       std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2629       ProcessedFiles.set(I);
2630       ProcessedFilesConditionVariable.notify_one();
2631     }
2632   };
2633 
2634   auto CloneAll = [&]() {
2635     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2636       {
2637         std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2638         if (!ProcessedFiles[I]) {
2639           ProcessedFilesConditionVariable.wait(
2640               LockGuard, [&]() { return ProcessedFiles[I]; });
2641         }
2642       }
2643 
2644       CloneLambda(I);
2645     }
2646     EmitLambda();
2647   };
2648 
2649   // To limit memory usage in the single threaded case, analyze and clone are
2650   // run sequentially so the OptContext is freed after processing each object
2651   // in endDebugObject.
2652   if (Options.Threads == 1) {
2653     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2654       AnalyzeLambda(I);
2655       CloneLambda(I);
2656     }
2657     EmitLambda();
2658   } else {
2659     ThreadPool Pool(hardware_concurrency(2));
2660     Pool.async(AnalyzeAll);
2661     Pool.async(CloneAll);
2662     Pool.wait();
2663   }
2664 
2665   if (Options.Statistics) {
2666     // Create a vector sorted in descending order by output size.
2667     std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
2668     for (auto &E : SizeByObject)
2669       Sorted.emplace_back(E.first(), E.second);
2670     llvm::sort(Sorted, [](auto &LHS, auto &RHS) {
2671       return LHS.second.Output > RHS.second.Output;
2672     });
2673 
2674     auto ComputePercentange = [](int64_t Input, int64_t Output) -> float {
2675       const float Difference = Output - Input;
2676       const float Sum = Input + Output;
2677       if (Sum == 0)
2678         return 0;
2679       return (Difference / (Sum / 2));
2680     };
2681 
2682     int64_t InputTotal = 0;
2683     int64_t OutputTotal = 0;
2684     const char *FormatStr = "{0,-45} {1,10}b  {2,10}b {3,8:P}\n";
2685 
2686     // Print header.
2687     outs() << ".debug_info section size (in bytes)\n";
2688     outs() << "----------------------------------------------------------------"
2689               "---------------\n";
2690     outs() << "Filename                                           Object       "
2691               "  dSYM   Change\n";
2692     outs() << "----------------------------------------------------------------"
2693               "---------------\n";
2694 
2695     // Print body.
2696     for (auto &E : Sorted) {
2697       InputTotal += E.second.Input;
2698       OutputTotal += E.second.Output;
2699       llvm::outs() << formatv(
2700           FormatStr, sys::path::filename(E.first).take_back(45), E.second.Input,
2701           E.second.Output, ComputePercentange(E.second.Input, E.second.Output));
2702     }
2703     // Print total and footer.
2704     outs() << "----------------------------------------------------------------"
2705               "---------------\n";
2706     llvm::outs() << formatv(FormatStr, "Total", InputTotal, OutputTotal,
2707                             ComputePercentange(InputTotal, OutputTotal));
2708     outs() << "----------------------------------------------------------------"
2709               "---------------\n\n";
2710   }
2711 
2712   return Error::success();
2713 }
2714 
verify(const DWARFFile & File)2715 bool DWARFLinker::verify(const DWARFFile &File) {
2716   assert(File.Dwarf);
2717 
2718   DIDumpOptions DumpOpts;
2719   if (!File.Dwarf->verify(llvm::outs(), DumpOpts.noImplicitRecursion())) {
2720     reportWarning("input verification failed", File);
2721     return false;
2722   }
2723   return true;
2724 }
2725 
2726 } // namespace llvm
2727