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