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