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