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