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