1 //===- DWARFContext.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/DebugInfo/DWARF/DWARFContext.h" 10 #include "llvm/ADT/MapVector.h" 11 #include "llvm/ADT/STLExtras.h" 12 #include "llvm/ADT/SmallString.h" 13 #include "llvm/ADT/SmallVector.h" 14 #include "llvm/ADT/StringRef.h" 15 #include "llvm/ADT/StringSwitch.h" 16 #include "llvm/BinaryFormat/Dwarf.h" 17 #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h" 18 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h" 19 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h" 20 #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h" 21 #include "llvm/DebugInfo/DWARF/DWARFDebugAddr.h" 22 #include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h" 23 #include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h" 24 #include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h" 25 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h" 26 #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h" 27 #include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h" 28 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h" 29 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h" 30 #include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h" 31 #include "llvm/DebugInfo/DWARF/DWARFDie.h" 32 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" 33 #include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h" 34 #include "llvm/DebugInfo/DWARF/DWARFListTable.h" 35 #include "llvm/DebugInfo/DWARF/DWARFLocationExpression.h" 36 #include "llvm/DebugInfo/DWARF/DWARFRelocMap.h" 37 #include "llvm/DebugInfo/DWARF/DWARFSection.h" 38 #include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h" 39 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h" 40 #include "llvm/DebugInfo/DWARF/DWARFVerifier.h" 41 #include "llvm/MC/TargetRegistry.h" 42 #include "llvm/Object/Decompressor.h" 43 #include "llvm/Object/MachO.h" 44 #include "llvm/Object/ObjectFile.h" 45 #include "llvm/Object/RelocationResolver.h" 46 #include "llvm/Support/Casting.h" 47 #include "llvm/Support/DataExtractor.h" 48 #include "llvm/Support/Error.h" 49 #include "llvm/Support/Format.h" 50 #include "llvm/Support/LEB128.h" 51 #include "llvm/Support/MemoryBuffer.h" 52 #include "llvm/Support/Path.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include <cstdint> 55 #include <deque> 56 #include <map> 57 #include <string> 58 #include <utility> 59 #include <vector> 60 61 using namespace llvm; 62 using namespace dwarf; 63 using namespace object; 64 65 #define DEBUG_TYPE "dwarf" 66 67 using DWARFLineTable = DWARFDebugLine::LineTable; 68 using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind; 69 using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind; 70 71 72 void fixupIndexV4(DWARFContext &C, DWARFUnitIndex &Index) { 73 using EntryType = DWARFUnitIndex::Entry::SectionContribution; 74 using EntryMap = DenseMap<uint32_t, EntryType>; 75 EntryMap Map; 76 const auto &DObj = C.getDWARFObj(); 77 if (DObj.getCUIndexSection().empty()) 78 return; 79 80 uint64_t Offset = 0; 81 uint32_t TruncOffset = 0; 82 DObj.forEachInfoDWOSections([&](const DWARFSection &S) { 83 if (!(C.getParseCUTUIndexManually() || 84 S.Data.size() >= std::numeric_limits<uint32_t>::max())) 85 return; 86 87 DWARFDataExtractor Data(DObj, S, C.isLittleEndian(), 0); 88 while (Data.isValidOffset(Offset)) { 89 DWARFUnitHeader Header; 90 if (Error ExtractionErr = Header.extract( 91 C, Data, &Offset, DWARFSectionKind::DW_SECT_INFO)) { 92 C.getWarningHandler()( 93 createError("Failed to parse CU header in DWP file: " + 94 toString(std::move(ExtractionErr)))); 95 Map.clear(); 96 break; 97 } 98 99 auto Iter = Map.insert({TruncOffset, 100 {Header.getOffset(), Header.getNextUnitOffset() - 101 Header.getOffset()}}); 102 if (!Iter.second) { 103 logAllUnhandledErrors( 104 createError("Collision occured between for truncated offset 0x" + 105 Twine::utohexstr(TruncOffset)), 106 errs()); 107 Map.clear(); 108 return; 109 } 110 111 Offset = Header.getNextUnitOffset(); 112 TruncOffset = Offset; 113 } 114 }); 115 116 if (Map.empty()) 117 return; 118 119 for (DWARFUnitIndex::Entry &E : Index.getMutableRows()) { 120 if (!E.isValid()) 121 continue; 122 DWARFUnitIndex::Entry::SectionContribution &CUOff = E.getContribution(); 123 auto Iter = Map.find(CUOff.getOffset()); 124 if (Iter == Map.end()) { 125 logAllUnhandledErrors(createError("Could not find CU offset 0x" + 126 Twine::utohexstr(CUOff.getOffset()) + 127 " in the Map"), 128 errs()); 129 break; 130 } 131 CUOff.setOffset(Iter->second.getOffset()); 132 if (CUOff.getOffset() != Iter->second.getOffset()) 133 logAllUnhandledErrors(createError("Length of CU in CU index doesn't " 134 "match calculated length at offset 0x" + 135 Twine::utohexstr(CUOff.getOffset())), 136 errs()); 137 } 138 } 139 140 void fixupIndexV5(DWARFContext &C, DWARFUnitIndex &Index) { 141 DenseMap<uint64_t, uint64_t> Map; 142 143 const auto &DObj = C.getDWARFObj(); 144 DObj.forEachInfoDWOSections([&](const DWARFSection &S) { 145 if (!(C.getParseCUTUIndexManually() || 146 S.Data.size() >= std::numeric_limits<uint32_t>::max())) 147 return; 148 DWARFDataExtractor Data(DObj, S, C.isLittleEndian(), 0); 149 uint64_t Offset = 0; 150 while (Data.isValidOffset(Offset)) { 151 DWARFUnitHeader Header; 152 if (Error ExtractionErr = Header.extract( 153 C, Data, &Offset, DWARFSectionKind::DW_SECT_INFO)) { 154 C.getWarningHandler()( 155 createError("Failed to parse CU header in DWP file: " + 156 toString(std::move(ExtractionErr)))); 157 break; 158 } 159 bool CU = Header.getUnitType() == DW_UT_split_compile; 160 uint64_t Sig = CU ? *Header.getDWOId() : Header.getTypeHash(); 161 Map[Sig] = Header.getOffset(); 162 Offset = Header.getNextUnitOffset(); 163 } 164 }); 165 if (Map.empty()) 166 return; 167 for (DWARFUnitIndex::Entry &E : Index.getMutableRows()) { 168 if (!E.isValid()) 169 continue; 170 DWARFUnitIndex::Entry::SectionContribution &CUOff = E.getContribution(); 171 auto Iter = Map.find(E.getSignature()); 172 if (Iter == Map.end()) { 173 logAllUnhandledErrors( 174 createError("Could not find unit with signature 0x" + 175 Twine::utohexstr(E.getSignature()) + " in the Map"), 176 errs()); 177 break; 178 } 179 CUOff.setOffset(Iter->second); 180 } 181 } 182 183 void fixupIndex(DWARFContext &C, DWARFUnitIndex &Index) { 184 if (Index.getVersion() < 5) 185 fixupIndexV4(C, Index); 186 else 187 fixupIndexV5(C, Index); 188 } 189 190 template <typename T> 191 static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj, 192 const DWARFSection &Section, StringRef StringSection, 193 bool IsLittleEndian) { 194 if (Cache) 195 return *Cache; 196 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0); 197 DataExtractor StrData(StringSection, IsLittleEndian, 0); 198 Cache = std::make_unique<T>(AccelSection, StrData); 199 if (Error E = Cache->extract()) 200 llvm::consumeError(std::move(E)); 201 return *Cache; 202 } 203 204 205 std::unique_ptr<DWARFDebugMacro> 206 DWARFContext::DWARFContextState::parseMacroOrMacinfo(MacroSecType SectionType) { 207 auto Macro = std::make_unique<DWARFDebugMacro>(); 208 auto ParseAndDump = [&](DWARFDataExtractor &Data, bool IsMacro) { 209 if (Error Err = IsMacro ? Macro->parseMacro(SectionType == MacroSection 210 ? D.compile_units() 211 : D.dwo_compile_units(), 212 SectionType == MacroSection 213 ? D.getStringExtractor() 214 : D.getStringDWOExtractor(), 215 Data) 216 : Macro->parseMacinfo(Data)) { 217 D.getRecoverableErrorHandler()(std::move(Err)); 218 Macro = nullptr; 219 } 220 }; 221 const DWARFObject &DObj = D.getDWARFObj(); 222 switch (SectionType) { 223 case MacinfoSection: { 224 DWARFDataExtractor Data(DObj.getMacinfoSection(), D.isLittleEndian(), 0); 225 ParseAndDump(Data, /*IsMacro=*/false); 226 break; 227 } 228 case MacinfoDwoSection: { 229 DWARFDataExtractor Data(DObj.getMacinfoDWOSection(), D.isLittleEndian(), 0); 230 ParseAndDump(Data, /*IsMacro=*/false); 231 break; 232 } 233 case MacroSection: { 234 DWARFDataExtractor Data(DObj, DObj.getMacroSection(), D.isLittleEndian(), 235 0); 236 ParseAndDump(Data, /*IsMacro=*/true); 237 break; 238 } 239 case MacroDwoSection: { 240 DWARFDataExtractor Data(DObj.getMacroDWOSection(), D.isLittleEndian(), 0); 241 ParseAndDump(Data, /*IsMacro=*/true); 242 break; 243 } 244 } 245 return Macro; 246 } 247 248 namespace { 249 class ThreadUnsafeDWARFContextState : public DWARFContext::DWARFContextState { 250 251 DWARFUnitVector NormalUnits; 252 std::optional<DenseMap<uint64_t, DWARFTypeUnit *>> NormalTypeUnits; 253 std::unique_ptr<DWARFUnitIndex> CUIndex; 254 std::unique_ptr<DWARFGdbIndex> GdbIndex; 255 std::unique_ptr<DWARFUnitIndex> TUIndex; 256 std::unique_ptr<DWARFDebugAbbrev> Abbrev; 257 std::unique_ptr<DWARFDebugLoc> Loc; 258 std::unique_ptr<DWARFDebugAranges> Aranges; 259 std::unique_ptr<DWARFDebugLine> Line; 260 std::unique_ptr<DWARFDebugFrame> DebugFrame; 261 std::unique_ptr<DWARFDebugFrame> EHFrame; 262 std::unique_ptr<DWARFDebugMacro> Macro; 263 std::unique_ptr<DWARFDebugMacro> Macinfo; 264 std::unique_ptr<DWARFDebugNames> Names; 265 std::unique_ptr<AppleAcceleratorTable> AppleNames; 266 std::unique_ptr<AppleAcceleratorTable> AppleTypes; 267 std::unique_ptr<AppleAcceleratorTable> AppleNamespaces; 268 std::unique_ptr<AppleAcceleratorTable> AppleObjC; 269 DWARFUnitVector DWOUnits; 270 std::optional<DenseMap<uint64_t, DWARFTypeUnit *>> DWOTypeUnits; 271 std::unique_ptr<DWARFDebugAbbrev> AbbrevDWO; 272 std::unique_ptr<DWARFDebugMacro> MacinfoDWO; 273 std::unique_ptr<DWARFDebugMacro> MacroDWO; 274 struct DWOFile { 275 object::OwningBinary<object::ObjectFile> File; 276 std::unique_ptr<DWARFContext> Context; 277 }; 278 StringMap<std::weak_ptr<DWOFile>> DWOFiles; 279 std::weak_ptr<DWOFile> DWP; 280 bool CheckedForDWP = false; 281 std::string DWPName; 282 283 public: 284 ThreadUnsafeDWARFContextState(DWARFContext &DC, std::string &DWP) : 285 DWARFContext::DWARFContextState(DC), 286 DWPName(std::move(DWP)) {} 287 288 DWARFUnitVector &getNormalUnits() override { 289 if (NormalUnits.empty()) { 290 const DWARFObject &DObj = D.getDWARFObj(); 291 DObj.forEachInfoSections([&](const DWARFSection &S) { 292 NormalUnits.addUnitsForSection(D, S, DW_SECT_INFO); 293 }); 294 NormalUnits.finishedInfoUnits(); 295 DObj.forEachTypesSections([&](const DWARFSection &S) { 296 NormalUnits.addUnitsForSection(D, S, DW_SECT_EXT_TYPES); 297 }); 298 } 299 return NormalUnits; 300 } 301 302 DWARFUnitVector &getDWOUnits(bool Lazy) override { 303 if (DWOUnits.empty()) { 304 const DWARFObject &DObj = D.getDWARFObj(); 305 306 DObj.forEachInfoDWOSections([&](const DWARFSection &S) { 307 DWOUnits.addUnitsForDWOSection(D, S, DW_SECT_INFO, Lazy); 308 }); 309 DWOUnits.finishedInfoUnits(); 310 DObj.forEachTypesDWOSections([&](const DWARFSection &S) { 311 DWOUnits.addUnitsForDWOSection(D, S, DW_SECT_EXT_TYPES, Lazy); 312 }); 313 } 314 return DWOUnits; 315 } 316 317 const DWARFDebugAbbrev *getDebugAbbrevDWO() override { 318 if (AbbrevDWO) 319 return AbbrevDWO.get(); 320 const DWARFObject &DObj = D.getDWARFObj(); 321 DataExtractor abbrData(DObj.getAbbrevDWOSection(), D.isLittleEndian(), 0); 322 AbbrevDWO = std::make_unique<DWARFDebugAbbrev>(abbrData); 323 return AbbrevDWO.get(); 324 } 325 326 const DWARFUnitIndex &getCUIndex() override { 327 if (CUIndex) 328 return *CUIndex; 329 330 DataExtractor Data(D.getDWARFObj().getCUIndexSection(), 331 D.isLittleEndian(), 0); 332 CUIndex = std::make_unique<DWARFUnitIndex>(DW_SECT_INFO); 333 if (CUIndex->parse(Data)) 334 fixupIndex(D, *CUIndex); 335 return *CUIndex; 336 } 337 const DWARFUnitIndex &getTUIndex() override { 338 if (TUIndex) 339 return *TUIndex; 340 341 DataExtractor Data(D.getDWARFObj().getTUIndexSection(), 342 D.isLittleEndian(), 0); 343 TUIndex = std::make_unique<DWARFUnitIndex>(DW_SECT_EXT_TYPES); 344 bool isParseSuccessful = TUIndex->parse(Data); 345 // If we are parsing TU-index and for .debug_types section we don't need 346 // to do anything. 347 if (isParseSuccessful && TUIndex->getVersion() != 2) 348 fixupIndex(D, *TUIndex); 349 return *TUIndex; 350 } 351 352 DWARFGdbIndex &getGdbIndex() override { 353 if (GdbIndex) 354 return *GdbIndex; 355 356 DataExtractor Data(D.getDWARFObj().getGdbIndexSection(), true /*LE*/, 0); 357 GdbIndex = std::make_unique<DWARFGdbIndex>(); 358 GdbIndex->parse(Data); 359 return *GdbIndex; 360 } 361 362 const DWARFDebugAbbrev *getDebugAbbrev() override { 363 if (Abbrev) 364 return Abbrev.get(); 365 366 DataExtractor Data(D.getDWARFObj().getAbbrevSection(), 367 D.isLittleEndian(), 0); 368 Abbrev = std::make_unique<DWARFDebugAbbrev>(Data); 369 return Abbrev.get(); 370 } 371 372 const DWARFDebugLoc *getDebugLoc() override { 373 if (Loc) 374 return Loc.get(); 375 376 const DWARFObject &DObj = D.getDWARFObj(); 377 // Assume all units have the same address byte size. 378 auto Data = 379 D.getNumCompileUnits() 380 ? DWARFDataExtractor(DObj, DObj.getLocSection(), D.isLittleEndian(), 381 D.getUnitAtIndex(0)->getAddressByteSize()) 382 : DWARFDataExtractor("", D.isLittleEndian(), 0); 383 Loc = std::make_unique<DWARFDebugLoc>(std::move(Data)); 384 return Loc.get(); 385 } 386 387 const DWARFDebugAranges *getDebugAranges() override { 388 if (Aranges) 389 return Aranges.get(); 390 391 Aranges = std::make_unique<DWARFDebugAranges>(); 392 Aranges->generate(&D); 393 return Aranges.get(); 394 } 395 396 Expected<const DWARFDebugLine::LineTable *> 397 getLineTableForUnit(DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) override { 398 if (!Line) 399 Line = std::make_unique<DWARFDebugLine>(); 400 401 auto UnitDIE = U->getUnitDIE(); 402 if (!UnitDIE) 403 return nullptr; 404 405 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list)); 406 if (!Offset) 407 return nullptr; // No line table for this compile unit. 408 409 uint64_t stmtOffset = *Offset + U->getLineTableOffset(); 410 // See if the line table is cached. 411 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset)) 412 return lt; 413 414 // Make sure the offset is good before we try to parse. 415 if (stmtOffset >= U->getLineSection().Data.size()) 416 return nullptr; 417 418 // We have to parse it first. 419 DWARFDataExtractor Data(U->getContext().getDWARFObj(), U->getLineSection(), 420 U->isLittleEndian(), U->getAddressByteSize()); 421 return Line->getOrParseLineTable(Data, stmtOffset, U->getContext(), U, 422 RecoverableErrorHandler); 423 424 } 425 426 void clearLineTableForUnit(DWARFUnit *U) override { 427 if (!Line) 428 return; 429 430 auto UnitDIE = U->getUnitDIE(); 431 if (!UnitDIE) 432 return; 433 434 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list)); 435 if (!Offset) 436 return; 437 438 uint64_t stmtOffset = *Offset + U->getLineTableOffset(); 439 Line->clearLineTable(stmtOffset); 440 } 441 442 Expected<const DWARFDebugFrame *> getDebugFrame() override { 443 if (DebugFrame) 444 return DebugFrame.get(); 445 const DWARFObject &DObj = D.getDWARFObj(); 446 const DWARFSection &DS = DObj.getFrameSection(); 447 448 // There's a "bug" in the DWARFv3 standard with respect to the target address 449 // size within debug frame sections. While DWARF is supposed to be independent 450 // of its container, FDEs have fields with size being "target address size", 451 // which isn't specified in DWARF in general. It's only specified for CUs, but 452 // .eh_frame can appear without a .debug_info section. Follow the example of 453 // other tools (libdwarf) and extract this from the container (ObjectFile 454 // provides this information). This problem is fixed in DWARFv4 455 // See this dwarf-discuss discussion for more details: 456 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html 457 DWARFDataExtractor Data(DObj, DS, D.isLittleEndian(), 458 DObj.getAddressSize()); 459 auto DF = 460 std::make_unique<DWARFDebugFrame>(D.getArch(), /*IsEH=*/false, 461 DS.Address); 462 if (Error E = DF->parse(Data)) 463 return std::move(E); 464 465 DebugFrame.swap(DF); 466 return DebugFrame.get(); 467 } 468 469 Expected<const DWARFDebugFrame *> getEHFrame() override { 470 if (EHFrame) 471 return EHFrame.get(); 472 const DWARFObject &DObj = D.getDWARFObj(); 473 474 const DWARFSection &DS = DObj.getEHFrameSection(); 475 DWARFDataExtractor Data(DObj, DS, D.isLittleEndian(), 476 DObj.getAddressSize()); 477 auto DF = 478 std::make_unique<DWARFDebugFrame>(D.getArch(), /*IsEH=*/true, 479 DS.Address); 480 if (Error E = DF->parse(Data)) 481 return std::move(E); 482 EHFrame.swap(DF); 483 return EHFrame.get(); 484 } 485 486 const DWARFDebugMacro *getDebugMacinfo() override { 487 if (!Macinfo) 488 Macinfo = parseMacroOrMacinfo(MacinfoSection); 489 return Macinfo.get(); 490 } 491 const DWARFDebugMacro *getDebugMacinfoDWO() override { 492 if (!MacinfoDWO) 493 MacinfoDWO = parseMacroOrMacinfo(MacinfoDwoSection); 494 return MacinfoDWO.get(); 495 } 496 const DWARFDebugMacro *getDebugMacro() override { 497 if (!Macro) 498 Macro = parseMacroOrMacinfo(MacroSection); 499 return Macro.get(); 500 } 501 const DWARFDebugMacro *getDebugMacroDWO() override { 502 if (!MacroDWO) 503 MacroDWO = parseMacroOrMacinfo(MacroDwoSection); 504 return MacroDWO.get(); 505 } 506 const DWARFDebugNames &getDebugNames() override { 507 const DWARFObject &DObj = D.getDWARFObj(); 508 return getAccelTable(Names, DObj, DObj.getNamesSection(), 509 DObj.getStrSection(), D.isLittleEndian()); 510 } 511 const AppleAcceleratorTable &getAppleNames() override { 512 const DWARFObject &DObj = D.getDWARFObj(); 513 return getAccelTable(AppleNames, DObj, DObj.getAppleNamesSection(), 514 DObj.getStrSection(), D.isLittleEndian()); 515 516 } 517 const AppleAcceleratorTable &getAppleTypes() override { 518 const DWARFObject &DObj = D.getDWARFObj(); 519 return getAccelTable(AppleTypes, DObj, DObj.getAppleTypesSection(), 520 DObj.getStrSection(), D.isLittleEndian()); 521 522 } 523 const AppleAcceleratorTable &getAppleNamespaces() override { 524 const DWARFObject &DObj = D.getDWARFObj(); 525 return getAccelTable(AppleNamespaces, DObj, 526 DObj.getAppleNamespacesSection(), 527 DObj.getStrSection(), D.isLittleEndian()); 528 529 } 530 const AppleAcceleratorTable &getAppleObjC() override { 531 const DWARFObject &DObj = D.getDWARFObj(); 532 return getAccelTable(AppleObjC, DObj, DObj.getAppleObjCSection(), 533 DObj.getStrSection(), D.isLittleEndian()); 534 } 535 536 std::shared_ptr<DWARFContext> 537 getDWOContext(StringRef AbsolutePath) override { 538 if (auto S = DWP.lock()) { 539 DWARFContext *Ctxt = S->Context.get(); 540 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt); 541 } 542 543 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath]; 544 545 if (auto S = Entry->lock()) { 546 DWARFContext *Ctxt = S->Context.get(); 547 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt); 548 } 549 550 const DWARFObject &DObj = D.getDWARFObj(); 551 552 Expected<OwningBinary<ObjectFile>> Obj = [&] { 553 if (!CheckedForDWP) { 554 SmallString<128> DWPName; 555 auto Obj = object::ObjectFile::createObjectFile( 556 this->DWPName.empty() 557 ? (DObj.getFileName() + ".dwp").toStringRef(DWPName) 558 : StringRef(this->DWPName)); 559 if (Obj) { 560 Entry = &DWP; 561 return Obj; 562 } else { 563 CheckedForDWP = true; 564 // TODO: Should this error be handled (maybe in a high verbosity mode) 565 // before falling back to .dwo files? 566 consumeError(Obj.takeError()); 567 } 568 } 569 570 return object::ObjectFile::createObjectFile(AbsolutePath); 571 }(); 572 573 if (!Obj) { 574 // TODO: Actually report errors helpfully. 575 consumeError(Obj.takeError()); 576 return nullptr; 577 } 578 579 auto S = std::make_shared<DWOFile>(); 580 S->File = std::move(Obj.get()); 581 // Allow multi-threaded access if there is a .dwp file as the CU index and 582 // TU index might be accessed from multiple threads. 583 bool ThreadSafe = isThreadSafe(); 584 S->Context = DWARFContext::create( 585 *S->File.getBinary(), DWARFContext::ProcessDebugRelocations::Ignore, 586 nullptr, "", WithColor::defaultErrorHandler, 587 WithColor::defaultWarningHandler, ThreadSafe); 588 *Entry = S; 589 auto *Ctxt = S->Context.get(); 590 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt); 591 } 592 593 bool isThreadSafe() const override { return false; } 594 595 const DenseMap<uint64_t, DWARFTypeUnit *> &getNormalTypeUnitMap() { 596 if (!NormalTypeUnits) { 597 NormalTypeUnits.emplace(); 598 for (const auto &U :D.normal_units()) { 599 if (DWARFTypeUnit *TU = dyn_cast<DWARFTypeUnit>(U.get())) 600 (*NormalTypeUnits)[TU->getTypeHash()] = TU; 601 } 602 } 603 return *NormalTypeUnits; 604 } 605 606 const DenseMap<uint64_t, DWARFTypeUnit *> &getDWOTypeUnitMap() { 607 if (!DWOTypeUnits) { 608 DWOTypeUnits.emplace(); 609 for (const auto &U :D.dwo_units()) { 610 if (DWARFTypeUnit *TU = dyn_cast<DWARFTypeUnit>(U.get())) 611 (*DWOTypeUnits)[TU->getTypeHash()] = TU; 612 } 613 } 614 return *DWOTypeUnits; 615 } 616 617 const DenseMap<uint64_t, DWARFTypeUnit *> & 618 getTypeUnitMap(bool IsDWO) override { 619 if (IsDWO) 620 return getDWOTypeUnitMap(); 621 else 622 return getNormalTypeUnitMap(); 623 } 624 625 626 }; 627 628 class ThreadSafeState : public ThreadUnsafeDWARFContextState { 629 std::recursive_mutex Mutex; 630 631 public: 632 ThreadSafeState(DWARFContext &DC, std::string &DWP) : 633 ThreadUnsafeDWARFContextState(DC, DWP) {} 634 635 DWARFUnitVector &getNormalUnits() override { 636 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 637 return ThreadUnsafeDWARFContextState::getNormalUnits(); 638 } 639 DWARFUnitVector &getDWOUnits(bool Lazy) override { 640 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 641 // We need to not do lazy parsing when we need thread safety as 642 // DWARFUnitVector, in lazy mode, will slowly add things to itself and 643 // will cause problems in a multi-threaded environment. 644 return ThreadUnsafeDWARFContextState::getDWOUnits(false); 645 } 646 const DWARFUnitIndex &getCUIndex() override { 647 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 648 return ThreadUnsafeDWARFContextState::getCUIndex(); 649 } 650 const DWARFDebugAbbrev *getDebugAbbrevDWO() override { 651 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 652 return ThreadUnsafeDWARFContextState::getDebugAbbrevDWO(); 653 } 654 655 const DWARFUnitIndex &getTUIndex() override { 656 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 657 return ThreadUnsafeDWARFContextState::getTUIndex(); 658 } 659 DWARFGdbIndex &getGdbIndex() override { 660 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 661 return ThreadUnsafeDWARFContextState::getGdbIndex(); 662 } 663 const DWARFDebugAbbrev *getDebugAbbrev() override { 664 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 665 return ThreadUnsafeDWARFContextState::getDebugAbbrev(); 666 } 667 const DWARFDebugLoc *getDebugLoc() override { 668 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 669 return ThreadUnsafeDWARFContextState::getDebugLoc(); 670 } 671 const DWARFDebugAranges *getDebugAranges() override { 672 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 673 return ThreadUnsafeDWARFContextState::getDebugAranges(); 674 } 675 Expected<const DWARFDebugLine::LineTable *> 676 getLineTableForUnit(DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) override { 677 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 678 return ThreadUnsafeDWARFContextState::getLineTableForUnit(U, RecoverableErrorHandler); 679 } 680 void clearLineTableForUnit(DWARFUnit *U) override { 681 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 682 return ThreadUnsafeDWARFContextState::clearLineTableForUnit(U); 683 } 684 Expected<const DWARFDebugFrame *> getDebugFrame() override { 685 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 686 return ThreadUnsafeDWARFContextState::getDebugFrame(); 687 } 688 Expected<const DWARFDebugFrame *> getEHFrame() override { 689 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 690 return ThreadUnsafeDWARFContextState::getEHFrame(); 691 } 692 const DWARFDebugMacro *getDebugMacinfo() override { 693 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 694 return ThreadUnsafeDWARFContextState::getDebugMacinfo(); 695 } 696 const DWARFDebugMacro *getDebugMacinfoDWO() override { 697 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 698 return ThreadUnsafeDWARFContextState::getDebugMacinfoDWO(); 699 } 700 const DWARFDebugMacro *getDebugMacro() override { 701 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 702 return ThreadUnsafeDWARFContextState::getDebugMacro(); 703 } 704 const DWARFDebugMacro *getDebugMacroDWO() override { 705 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 706 return ThreadUnsafeDWARFContextState::getDebugMacroDWO(); 707 } 708 const DWARFDebugNames &getDebugNames() override { 709 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 710 return ThreadUnsafeDWARFContextState::getDebugNames(); 711 } 712 const AppleAcceleratorTable &getAppleNames() override { 713 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 714 return ThreadUnsafeDWARFContextState::getAppleNames(); 715 } 716 const AppleAcceleratorTable &getAppleTypes() override { 717 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 718 return ThreadUnsafeDWARFContextState::getAppleTypes(); 719 } 720 const AppleAcceleratorTable &getAppleNamespaces() override { 721 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 722 return ThreadUnsafeDWARFContextState::getAppleNamespaces(); 723 } 724 const AppleAcceleratorTable &getAppleObjC() override { 725 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 726 return ThreadUnsafeDWARFContextState::getAppleObjC(); 727 } 728 std::shared_ptr<DWARFContext> 729 getDWOContext(StringRef AbsolutePath) override { 730 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 731 return ThreadUnsafeDWARFContextState::getDWOContext(AbsolutePath); 732 } 733 734 bool isThreadSafe() const override { return true; } 735 736 const DenseMap<uint64_t, DWARFTypeUnit *> & 737 getTypeUnitMap(bool IsDWO) override { 738 std::unique_lock<std::recursive_mutex> LockGuard(Mutex); 739 return ThreadUnsafeDWARFContextState::getTypeUnitMap(IsDWO); 740 } 741 }; 742 } // namespace 743 744 DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj, 745 std::string DWPName, 746 std::function<void(Error)> RecoverableErrorHandler, 747 std::function<void(Error)> WarningHandler, 748 bool ThreadSafe) 749 : DIContext(CK_DWARF), 750 RecoverableErrorHandler(RecoverableErrorHandler), 751 WarningHandler(WarningHandler), DObj(std::move(DObj)) { 752 if (ThreadSafe) 753 State = std::make_unique<ThreadSafeState>(*this, DWPName); 754 else 755 State = std::make_unique<ThreadUnsafeDWARFContextState>(*this, DWPName); 756 } 757 758 DWARFContext::~DWARFContext() = default; 759 760 /// Dump the UUID load command. 761 static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) { 762 auto *MachO = dyn_cast<MachOObjectFile>(&Obj); 763 if (!MachO) 764 return; 765 for (auto LC : MachO->load_commands()) { 766 raw_ostream::uuid_t UUID; 767 if (LC.C.cmd == MachO::LC_UUID) { 768 if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) { 769 OS << "error: UUID load command is too short.\n"; 770 return; 771 } 772 OS << "UUID: "; 773 memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID)); 774 OS.write_uuid(UUID); 775 Triple T = MachO->getArchTriple(); 776 OS << " (" << T.getArchName() << ')'; 777 OS << ' ' << MachO->getFileName() << '\n'; 778 } 779 } 780 } 781 782 using ContributionCollection = 783 std::vector<std::optional<StrOffsetsContributionDescriptor>>; 784 785 // Collect all the contributions to the string offsets table from all units, 786 // sort them by their starting offsets and remove duplicates. 787 static ContributionCollection 788 collectContributionData(DWARFContext::unit_iterator_range Units) { 789 ContributionCollection Contributions; 790 for (const auto &U : Units) 791 if (const auto &C = U->getStringOffsetsTableContribution()) 792 Contributions.push_back(C); 793 // Sort the contributions so that any invalid ones are placed at 794 // the start of the contributions vector. This way they are reported 795 // first. 796 llvm::sort(Contributions, 797 [](const std::optional<StrOffsetsContributionDescriptor> &L, 798 const std::optional<StrOffsetsContributionDescriptor> &R) { 799 if (L && R) 800 return L->Base < R->Base; 801 return R.has_value(); 802 }); 803 804 // Uniquify contributions, as it is possible that units (specifically 805 // type units in dwo or dwp files) share contributions. We don't want 806 // to report them more than once. 807 Contributions.erase( 808 llvm::unique( 809 Contributions, 810 [](const std::optional<StrOffsetsContributionDescriptor> &L, 811 const std::optional<StrOffsetsContributionDescriptor> &R) { 812 if (L && R) 813 return L->Base == R->Base && L->Size == R->Size; 814 return false; 815 }), 816 Contributions.end()); 817 return Contributions; 818 } 819 820 // Dump a DWARF string offsets section. This may be a DWARF v5 formatted 821 // string offsets section, where each compile or type unit contributes a 822 // number of entries (string offsets), with each contribution preceded by 823 // a header containing size and version number. Alternatively, it may be a 824 // monolithic series of string offsets, as generated by the pre-DWARF v5 825 // implementation of split DWARF; however, in that case we still need to 826 // collect contributions of units because the size of the offsets (4 or 8 827 // bytes) depends on the format of the referencing unit (DWARF32 or DWARF64). 828 static void dumpStringOffsetsSection(raw_ostream &OS, DIDumpOptions DumpOpts, 829 StringRef SectionName, 830 const DWARFObject &Obj, 831 const DWARFSection &StringOffsetsSection, 832 StringRef StringSection, 833 DWARFContext::unit_iterator_range Units, 834 bool LittleEndian) { 835 auto Contributions = collectContributionData(Units); 836 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0); 837 DataExtractor StrData(StringSection, LittleEndian, 0); 838 uint64_t SectionSize = StringOffsetsSection.Data.size(); 839 uint64_t Offset = 0; 840 for (auto &Contribution : Contributions) { 841 // Report an ill-formed contribution. 842 if (!Contribution) { 843 OS << "error: invalid contribution to string offsets table in section ." 844 << SectionName << ".\n"; 845 return; 846 } 847 848 dwarf::DwarfFormat Format = Contribution->getFormat(); 849 int OffsetDumpWidth = 2 * dwarf::getDwarfOffsetByteSize(Format); 850 uint16_t Version = Contribution->getVersion(); 851 uint64_t ContributionHeader = Contribution->Base; 852 // In DWARF v5 there is a contribution header that immediately precedes 853 // the string offsets base (the location we have previously retrieved from 854 // the CU DIE's DW_AT_str_offsets attribute). The header is located either 855 // 8 or 16 bytes before the base, depending on the contribution's format. 856 if (Version >= 5) 857 ContributionHeader -= Format == DWARF32 ? 8 : 16; 858 859 // Detect overlapping contributions. 860 if (Offset > ContributionHeader) { 861 DumpOpts.RecoverableErrorHandler(createStringError( 862 errc::invalid_argument, 863 "overlapping contributions to string offsets table in section .%s.", 864 SectionName.data())); 865 } 866 // Report a gap in the table. 867 if (Offset < ContributionHeader) { 868 OS << format("0x%8.8" PRIx64 ": Gap, length = ", Offset); 869 OS << (ContributionHeader - Offset) << "\n"; 870 } 871 OS << format("0x%8.8" PRIx64 ": ", ContributionHeader); 872 // In DWARF v5 the contribution size in the descriptor does not equal 873 // the originally encoded length (it does not contain the length of the 874 // version field and the padding, a total of 4 bytes). Add them back in 875 // for reporting. 876 OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 0 : 4)) 877 << ", Format = " << dwarf::FormatString(Format) 878 << ", Version = " << Version << "\n"; 879 880 Offset = Contribution->Base; 881 unsigned EntrySize = Contribution->getDwarfOffsetByteSize(); 882 while (Offset - Contribution->Base < Contribution->Size) { 883 OS << format("0x%8.8" PRIx64 ": ", Offset); 884 uint64_t StringOffset = 885 StrOffsetExt.getRelocatedValue(EntrySize, &Offset); 886 OS << format("%0*" PRIx64 " ", OffsetDumpWidth, StringOffset); 887 const char *S = StrData.getCStr(&StringOffset); 888 if (S) 889 OS << format("\"%s\"", S); 890 OS << "\n"; 891 } 892 } 893 // Report a gap at the end of the table. 894 if (Offset < SectionSize) { 895 OS << format("0x%8.8" PRIx64 ": Gap, length = ", Offset); 896 OS << (SectionSize - Offset) << "\n"; 897 } 898 } 899 900 // Dump the .debug_addr section. 901 static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData, 902 DIDumpOptions DumpOpts, uint16_t Version, 903 uint8_t AddrSize) { 904 uint64_t Offset = 0; 905 while (AddrData.isValidOffset(Offset)) { 906 DWARFDebugAddrTable AddrTable; 907 uint64_t TableOffset = Offset; 908 if (Error Err = AddrTable.extract(AddrData, &Offset, Version, AddrSize, 909 DumpOpts.WarningHandler)) { 910 DumpOpts.RecoverableErrorHandler(std::move(Err)); 911 // Keep going after an error, if we can, assuming that the length field 912 // could be read. If it couldn't, stop reading the section. 913 if (auto TableLength = AddrTable.getFullLength()) { 914 Offset = TableOffset + *TableLength; 915 continue; 916 } 917 break; 918 } 919 AddrTable.dump(OS, DumpOpts); 920 } 921 } 922 923 // Dump the .debug_rnglists or .debug_rnglists.dwo section (DWARF v5). 924 static void dumpRnglistsSection( 925 raw_ostream &OS, DWARFDataExtractor &rnglistData, 926 llvm::function_ref<std::optional<object::SectionedAddress>(uint32_t)> 927 LookupPooledAddress, 928 DIDumpOptions DumpOpts) { 929 uint64_t Offset = 0; 930 while (rnglistData.isValidOffset(Offset)) { 931 llvm::DWARFDebugRnglistTable Rnglists; 932 uint64_t TableOffset = Offset; 933 if (Error Err = Rnglists.extract(rnglistData, &Offset)) { 934 DumpOpts.RecoverableErrorHandler(std::move(Err)); 935 uint64_t Length = Rnglists.length(); 936 // Keep going after an error, if we can, assuming that the length field 937 // could be read. If it couldn't, stop reading the section. 938 if (Length == 0) 939 break; 940 Offset = TableOffset + Length; 941 } else { 942 Rnglists.dump(rnglistData, OS, LookupPooledAddress, DumpOpts); 943 } 944 } 945 } 946 947 948 static void dumpLoclistsSection(raw_ostream &OS, DIDumpOptions DumpOpts, 949 DWARFDataExtractor Data, const DWARFObject &Obj, 950 std::optional<uint64_t> DumpOffset) { 951 uint64_t Offset = 0; 952 953 while (Data.isValidOffset(Offset)) { 954 DWARFListTableHeader Header(".debug_loclists", "locations"); 955 if (Error E = Header.extract(Data, &Offset)) { 956 DumpOpts.RecoverableErrorHandler(std::move(E)); 957 return; 958 } 959 960 Header.dump(Data, OS, DumpOpts); 961 962 uint64_t EndOffset = Header.length() + Header.getHeaderOffset(); 963 Data.setAddressSize(Header.getAddrSize()); 964 DWARFDebugLoclists Loc(Data, Header.getVersion()); 965 if (DumpOffset) { 966 if (DumpOffset >= Offset && DumpOffset < EndOffset) { 967 Offset = *DumpOffset; 968 Loc.dumpLocationList(&Offset, OS, /*BaseAddr=*/std::nullopt, Obj, 969 nullptr, DumpOpts, /*Indent=*/0); 970 OS << "\n"; 971 return; 972 } 973 } else { 974 Loc.dumpRange(Offset, EndOffset - Offset, OS, Obj, DumpOpts); 975 } 976 Offset = EndOffset; 977 } 978 } 979 980 static void dumpPubTableSection(raw_ostream &OS, DIDumpOptions DumpOpts, 981 DWARFDataExtractor Data, bool GnuStyle) { 982 DWARFDebugPubTable Table; 983 Table.extract(Data, GnuStyle, DumpOpts.RecoverableErrorHandler); 984 Table.dump(OS); 985 } 986 987 void DWARFContext::dump( 988 raw_ostream &OS, DIDumpOptions DumpOpts, 989 std::array<std::optional<uint64_t>, DIDT_ID_Count> DumpOffsets) { 990 uint64_t DumpType = DumpOpts.DumpType; 991 992 StringRef Extension = sys::path::extension(DObj->getFileName()); 993 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp"); 994 995 // Print UUID header. 996 const auto *ObjFile = DObj->getFile(); 997 if (DumpType & DIDT_UUID) 998 dumpUUID(OS, *ObjFile); 999 1000 // Print a header for each explicitly-requested section. 1001 // Otherwise just print one for non-empty sections. 1002 // Only print empty .dwo section headers when dumping a .dwo file. 1003 bool Explicit = DumpType != DIDT_All && !IsDWO; 1004 bool ExplicitDWO = Explicit && IsDWO; 1005 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID, 1006 StringRef Section) -> std::optional<uint64_t> * { 1007 unsigned Mask = 1U << ID; 1008 bool Should = (DumpType & Mask) && (Explicit || !Section.empty()); 1009 if (!Should) 1010 return nullptr; 1011 OS << "\n" << Name << " contents:\n"; 1012 return &DumpOffsets[ID]; 1013 }; 1014 1015 // Dump individual sections. 1016 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev, 1017 DObj->getAbbrevSection())) 1018 getDebugAbbrev()->dump(OS); 1019 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev, 1020 DObj->getAbbrevDWOSection())) 1021 getDebugAbbrevDWO()->dump(OS); 1022 1023 auto dumpDebugInfo = [&](const char *Name, unit_iterator_range Units) { 1024 OS << '\n' << Name << " contents:\n"; 1025 if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugInfo]) 1026 for (const auto &U : Units) { 1027 U->getDIEForOffset(*DumpOffset) 1028 .dump(OS, 0, DumpOpts.noImplicitRecursion()); 1029 DWARFDie CUDie = U->getUnitDIE(false); 1030 DWARFDie CUNonSkeletonDie = U->getNonSkeletonUnitDIE(false); 1031 if (CUNonSkeletonDie && CUDie != CUNonSkeletonDie) { 1032 CUNonSkeletonDie.getDwarfUnit() 1033 ->getDIEForOffset(*DumpOffset) 1034 .dump(OS, 0, DumpOpts.noImplicitRecursion()); 1035 } 1036 } 1037 else 1038 for (const auto &U : Units) 1039 U->dump(OS, DumpOpts); 1040 }; 1041 if ((DumpType & DIDT_DebugInfo)) { 1042 if (Explicit || getNumCompileUnits()) 1043 dumpDebugInfo(".debug_info", info_section_units()); 1044 if (ExplicitDWO || getNumDWOCompileUnits()) 1045 dumpDebugInfo(".debug_info.dwo", dwo_info_section_units()); 1046 } 1047 1048 auto dumpDebugType = [&](const char *Name, unit_iterator_range Units) { 1049 OS << '\n' << Name << " contents:\n"; 1050 for (const auto &U : Units) 1051 if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugTypes]) 1052 U->getDIEForOffset(*DumpOffset) 1053 .dump(OS, 0, DumpOpts.noImplicitRecursion()); 1054 else 1055 U->dump(OS, DumpOpts); 1056 }; 1057 if ((DumpType & DIDT_DebugTypes)) { 1058 if (Explicit || getNumTypeUnits()) 1059 dumpDebugType(".debug_types", types_section_units()); 1060 if (ExplicitDWO || getNumDWOTypeUnits()) 1061 dumpDebugType(".debug_types.dwo", dwo_types_section_units()); 1062 } 1063 1064 DIDumpOptions LLDumpOpts = DumpOpts; 1065 if (LLDumpOpts.Verbose) 1066 LLDumpOpts.DisplayRawContents = true; 1067 1068 if (const auto *Off = shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc, 1069 DObj->getLocSection().Data)) { 1070 getDebugLoc()->dump(OS, *DObj, LLDumpOpts, *Off); 1071 } 1072 if (const auto *Off = 1073 shouldDump(Explicit, ".debug_loclists", DIDT_ID_DebugLoclists, 1074 DObj->getLoclistsSection().Data)) { 1075 DWARFDataExtractor Data(*DObj, DObj->getLoclistsSection(), isLittleEndian(), 1076 0); 1077 dumpLoclistsSection(OS, LLDumpOpts, Data, *DObj, *Off); 1078 } 1079 if (const auto *Off = 1080 shouldDump(ExplicitDWO, ".debug_loclists.dwo", DIDT_ID_DebugLoclists, 1081 DObj->getLoclistsDWOSection().Data)) { 1082 DWARFDataExtractor Data(*DObj, DObj->getLoclistsDWOSection(), 1083 isLittleEndian(), 0); 1084 dumpLoclistsSection(OS, LLDumpOpts, Data, *DObj, *Off); 1085 } 1086 1087 if (const auto *Off = 1088 shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc, 1089 DObj->getLocDWOSection().Data)) { 1090 DWARFDataExtractor Data(*DObj, DObj->getLocDWOSection(), isLittleEndian(), 1091 4); 1092 DWARFDebugLoclists Loc(Data, /*Version=*/4); 1093 if (*Off) { 1094 uint64_t Offset = **Off; 1095 Loc.dumpLocationList(&Offset, OS, 1096 /*BaseAddr=*/std::nullopt, *DObj, nullptr, 1097 LLDumpOpts, 1098 /*Indent=*/0); 1099 OS << "\n"; 1100 } else { 1101 Loc.dumpRange(0, Data.getData().size(), OS, *DObj, LLDumpOpts); 1102 } 1103 } 1104 1105 if (const std::optional<uint64_t> *Off = 1106 shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame, 1107 DObj->getFrameSection().Data)) { 1108 if (Expected<const DWARFDebugFrame *> DF = getDebugFrame()) 1109 (*DF)->dump(OS, DumpOpts, *Off); 1110 else 1111 RecoverableErrorHandler(DF.takeError()); 1112 } 1113 1114 if (const std::optional<uint64_t> *Off = 1115 shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame, 1116 DObj->getEHFrameSection().Data)) { 1117 if (Expected<const DWARFDebugFrame *> DF = getEHFrame()) 1118 (*DF)->dump(OS, DumpOpts, *Off); 1119 else 1120 RecoverableErrorHandler(DF.takeError()); 1121 } 1122 1123 if (shouldDump(Explicit, ".debug_macro", DIDT_ID_DebugMacro, 1124 DObj->getMacroSection().Data)) { 1125 if (auto Macro = getDebugMacro()) 1126 Macro->dump(OS); 1127 } 1128 1129 if (shouldDump(Explicit, ".debug_macro.dwo", DIDT_ID_DebugMacro, 1130 DObj->getMacroDWOSection())) { 1131 if (auto MacroDWO = getDebugMacroDWO()) 1132 MacroDWO->dump(OS); 1133 } 1134 1135 if (shouldDump(Explicit, ".debug_macinfo", DIDT_ID_DebugMacro, 1136 DObj->getMacinfoSection())) { 1137 if (auto Macinfo = getDebugMacinfo()) 1138 Macinfo->dump(OS); 1139 } 1140 1141 if (shouldDump(Explicit, ".debug_macinfo.dwo", DIDT_ID_DebugMacro, 1142 DObj->getMacinfoDWOSection())) { 1143 if (auto MacinfoDWO = getDebugMacinfoDWO()) 1144 MacinfoDWO->dump(OS); 1145 } 1146 1147 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges, 1148 DObj->getArangesSection())) { 1149 uint64_t offset = 0; 1150 DWARFDataExtractor arangesData(DObj->getArangesSection(), isLittleEndian(), 1151 0); 1152 DWARFDebugArangeSet set; 1153 while (arangesData.isValidOffset(offset)) { 1154 if (Error E = 1155 set.extract(arangesData, &offset, DumpOpts.WarningHandler)) { 1156 RecoverableErrorHandler(std::move(E)); 1157 break; 1158 } 1159 set.dump(OS); 1160 } 1161 } 1162 1163 auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser, 1164 DIDumpOptions DumpOpts, 1165 std::optional<uint64_t> DumpOffset) { 1166 while (!Parser.done()) { 1167 if (DumpOffset && Parser.getOffset() != *DumpOffset) { 1168 Parser.skip(DumpOpts.WarningHandler, DumpOpts.WarningHandler); 1169 continue; 1170 } 1171 OS << "debug_line[" << format("0x%8.8" PRIx64, Parser.getOffset()) 1172 << "]\n"; 1173 Parser.parseNext(DumpOpts.WarningHandler, DumpOpts.WarningHandler, &OS, 1174 DumpOpts.Verbose); 1175 } 1176 }; 1177 1178 auto DumpStrSection = [&](StringRef Section) { 1179 DataExtractor StrData(Section, isLittleEndian(), 0); 1180 uint64_t Offset = 0; 1181 uint64_t StrOffset = 0; 1182 while (StrData.isValidOffset(Offset)) { 1183 Error Err = Error::success(); 1184 const char *CStr = StrData.getCStr(&Offset, &Err); 1185 if (Err) { 1186 DumpOpts.WarningHandler(std::move(Err)); 1187 return; 1188 } 1189 OS << format("0x%8.8" PRIx64 ": \"", StrOffset); 1190 OS.write_escaped(CStr); 1191 OS << "\"\n"; 1192 StrOffset = Offset; 1193 } 1194 }; 1195 1196 if (const auto *Off = shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine, 1197 DObj->getLineSection().Data)) { 1198 DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(), 1199 0); 1200 DWARFDebugLine::SectionParser Parser(LineData, *this, normal_units()); 1201 DumpLineSection(Parser, DumpOpts, *Off); 1202 } 1203 1204 if (const auto *Off = 1205 shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine, 1206 DObj->getLineDWOSection().Data)) { 1207 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(), 1208 isLittleEndian(), 0); 1209 DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_units()); 1210 DumpLineSection(Parser, DumpOpts, *Off); 1211 } 1212 1213 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex, 1214 DObj->getCUIndexSection())) { 1215 getCUIndex().dump(OS); 1216 } 1217 1218 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex, 1219 DObj->getTUIndexSection())) { 1220 getTUIndex().dump(OS); 1221 } 1222 1223 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr, 1224 DObj->getStrSection())) 1225 DumpStrSection(DObj->getStrSection()); 1226 1227 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr, 1228 DObj->getStrDWOSection())) 1229 DumpStrSection(DObj->getStrDWOSection()); 1230 1231 if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr, 1232 DObj->getLineStrSection())) 1233 DumpStrSection(DObj->getLineStrSection()); 1234 1235 if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr, 1236 DObj->getAddrSection().Data)) { 1237 DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(), 1238 isLittleEndian(), 0); 1239 dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize()); 1240 } 1241 1242 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges, 1243 DObj->getRangesSection().Data)) { 1244 uint8_t savedAddressByteSize = getCUAddrSize(); 1245 DWARFDataExtractor rangesData(*DObj, DObj->getRangesSection(), 1246 isLittleEndian(), savedAddressByteSize); 1247 uint64_t offset = 0; 1248 DWARFDebugRangeList rangeList; 1249 while (rangesData.isValidOffset(offset)) { 1250 if (Error E = rangeList.extract(rangesData, &offset)) { 1251 DumpOpts.RecoverableErrorHandler(std::move(E)); 1252 break; 1253 } 1254 rangeList.dump(OS); 1255 } 1256 } 1257 1258 auto LookupPooledAddress = 1259 [&](uint32_t Index) -> std::optional<SectionedAddress> { 1260 const auto &CUs = compile_units(); 1261 auto I = CUs.begin(); 1262 if (I == CUs.end()) 1263 return std::nullopt; 1264 return (*I)->getAddrOffsetSectionItem(Index); 1265 }; 1266 1267 if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists, 1268 DObj->getRnglistsSection().Data)) { 1269 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(), 1270 isLittleEndian(), 0); 1271 dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts); 1272 } 1273 1274 if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists, 1275 DObj->getRnglistsDWOSection().Data)) { 1276 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(), 1277 isLittleEndian(), 0); 1278 dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts); 1279 } 1280 1281 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames, 1282 DObj->getPubnamesSection().Data)) { 1283 DWARFDataExtractor PubTableData(*DObj, DObj->getPubnamesSection(), 1284 isLittleEndian(), 0); 1285 dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/false); 1286 } 1287 1288 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes, 1289 DObj->getPubtypesSection().Data)) { 1290 DWARFDataExtractor PubTableData(*DObj, DObj->getPubtypesSection(), 1291 isLittleEndian(), 0); 1292 dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/false); 1293 } 1294 1295 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames, 1296 DObj->getGnuPubnamesSection().Data)) { 1297 DWARFDataExtractor PubTableData(*DObj, DObj->getGnuPubnamesSection(), 1298 isLittleEndian(), 0); 1299 dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/true); 1300 } 1301 1302 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes, 1303 DObj->getGnuPubtypesSection().Data)) { 1304 DWARFDataExtractor PubTableData(*DObj, DObj->getGnuPubtypesSection(), 1305 isLittleEndian(), 0); 1306 dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/true); 1307 } 1308 1309 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets, 1310 DObj->getStrOffsetsSection().Data)) 1311 dumpStringOffsetsSection( 1312 OS, DumpOpts, "debug_str_offsets", *DObj, DObj->getStrOffsetsSection(), 1313 DObj->getStrSection(), normal_units(), isLittleEndian()); 1314 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets, 1315 DObj->getStrOffsetsDWOSection().Data)) 1316 dumpStringOffsetsSection(OS, DumpOpts, "debug_str_offsets.dwo", *DObj, 1317 DObj->getStrOffsetsDWOSection(), 1318 DObj->getStrDWOSection(), dwo_units(), 1319 isLittleEndian()); 1320 1321 if (shouldDump(Explicit, ".gdb_index", DIDT_ID_GdbIndex, 1322 DObj->getGdbIndexSection())) { 1323 getGdbIndex().dump(OS); 1324 } 1325 1326 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames, 1327 DObj->getAppleNamesSection().Data)) 1328 getAppleNames().dump(OS); 1329 1330 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes, 1331 DObj->getAppleTypesSection().Data)) 1332 getAppleTypes().dump(OS); 1333 1334 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces, 1335 DObj->getAppleNamespacesSection().Data)) 1336 getAppleNamespaces().dump(OS); 1337 1338 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC, 1339 DObj->getAppleObjCSection().Data)) 1340 getAppleObjC().dump(OS); 1341 if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames, 1342 DObj->getNamesSection().Data)) 1343 getDebugNames().dump(OS); 1344 } 1345 1346 DWARFTypeUnit *DWARFContext::getTypeUnitForHash(uint64_t Hash, bool IsDWO) { 1347 DWARFUnitVector &DWOUnits = State->getDWOUnits(); 1348 if (const auto &TUI = getTUIndex()) { 1349 if (const auto *R = TUI.getFromHash(Hash)) 1350 return dyn_cast_or_null<DWARFTypeUnit>( 1351 DWOUnits.getUnitForIndexEntry(*R)); 1352 return nullptr; 1353 } 1354 return State->getTypeUnitMap(IsDWO).lookup(Hash); 1355 } 1356 1357 DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) { 1358 DWARFUnitVector &DWOUnits = State->getDWOUnits(LazyParse); 1359 1360 if (const auto &CUI = getCUIndex()) { 1361 if (const auto *R = CUI.getFromHash(Hash)) 1362 return dyn_cast_or_null<DWARFCompileUnit>( 1363 DWOUnits.getUnitForIndexEntry(*R)); 1364 return nullptr; 1365 } 1366 1367 // If there's no index, just search through the CUs in the DWO - there's 1368 // probably only one unless this is something like LTO - though an in-process 1369 // built/cached lookup table could be used in that case to improve repeated 1370 // lookups of different CUs in the DWO. 1371 for (const auto &DWOCU : dwo_compile_units()) { 1372 // Might not have parsed DWO ID yet. 1373 if (!DWOCU->getDWOId()) { 1374 if (std::optional<uint64_t> DWOId = 1375 toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id))) 1376 DWOCU->setDWOId(*DWOId); 1377 else 1378 // No DWO ID? 1379 continue; 1380 } 1381 if (DWOCU->getDWOId() == Hash) 1382 return dyn_cast<DWARFCompileUnit>(DWOCU.get()); 1383 } 1384 return nullptr; 1385 } 1386 1387 DWARFDie DWARFContext::getDIEForOffset(uint64_t Offset) { 1388 if (auto *CU = State->getNormalUnits().getUnitForOffset(Offset)) 1389 return CU->getDIEForOffset(Offset); 1390 return DWARFDie(); 1391 } 1392 1393 bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) { 1394 bool Success = true; 1395 DWARFVerifier verifier(OS, *this, DumpOpts); 1396 1397 Success &= verifier.handleDebugAbbrev(); 1398 if (DumpOpts.DumpType & DIDT_DebugCUIndex) 1399 Success &= verifier.handleDebugCUIndex(); 1400 if (DumpOpts.DumpType & DIDT_DebugTUIndex) 1401 Success &= verifier.handleDebugTUIndex(); 1402 if (DumpOpts.DumpType & DIDT_DebugInfo) 1403 Success &= verifier.handleDebugInfo(); 1404 if (DumpOpts.DumpType & DIDT_DebugLine) 1405 Success &= verifier.handleDebugLine(); 1406 if (DumpOpts.DumpType & DIDT_DebugStrOffsets) 1407 Success &= verifier.handleDebugStrOffsets(); 1408 Success &= verifier.handleAccelTables(); 1409 verifier.summarize(); 1410 return Success; 1411 } 1412 1413 const DWARFUnitIndex &DWARFContext::getCUIndex() { 1414 return State->getCUIndex(); 1415 } 1416 1417 const DWARFUnitIndex &DWARFContext::getTUIndex() { 1418 return State->getTUIndex(); 1419 } 1420 1421 DWARFGdbIndex &DWARFContext::getGdbIndex() { 1422 return State->getGdbIndex(); 1423 } 1424 1425 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() { 1426 return State->getDebugAbbrev(); 1427 } 1428 1429 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() { 1430 return State->getDebugAbbrevDWO(); 1431 } 1432 1433 const DWARFDebugLoc *DWARFContext::getDebugLoc() { 1434 return State->getDebugLoc(); 1435 } 1436 1437 const DWARFDebugAranges *DWARFContext::getDebugAranges() { 1438 return State->getDebugAranges(); 1439 } 1440 1441 Expected<const DWARFDebugFrame *> DWARFContext::getDebugFrame() { 1442 return State->getDebugFrame(); 1443 } 1444 1445 Expected<const DWARFDebugFrame *> DWARFContext::getEHFrame() { 1446 return State->getEHFrame(); 1447 } 1448 1449 const DWARFDebugMacro *DWARFContext::getDebugMacro() { 1450 return State->getDebugMacro(); 1451 } 1452 1453 const DWARFDebugMacro *DWARFContext::getDebugMacroDWO() { 1454 return State->getDebugMacroDWO(); 1455 } 1456 1457 const DWARFDebugMacro *DWARFContext::getDebugMacinfo() { 1458 return State->getDebugMacinfo(); 1459 } 1460 1461 const DWARFDebugMacro *DWARFContext::getDebugMacinfoDWO() { 1462 return State->getDebugMacinfoDWO(); 1463 } 1464 1465 1466 const DWARFDebugNames &DWARFContext::getDebugNames() { 1467 return State->getDebugNames(); 1468 } 1469 1470 const AppleAcceleratorTable &DWARFContext::getAppleNames() { 1471 return State->getAppleNames(); 1472 } 1473 1474 const AppleAcceleratorTable &DWARFContext::getAppleTypes() { 1475 return State->getAppleTypes(); 1476 } 1477 1478 const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() { 1479 return State->getAppleNamespaces(); 1480 } 1481 1482 const AppleAcceleratorTable &DWARFContext::getAppleObjC() { 1483 return State->getAppleObjC(); 1484 } 1485 1486 const DWARFDebugLine::LineTable * 1487 DWARFContext::getLineTableForUnit(DWARFUnit *U) { 1488 Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable = 1489 getLineTableForUnit(U, WarningHandler); 1490 if (!ExpectedLineTable) { 1491 WarningHandler(ExpectedLineTable.takeError()); 1492 return nullptr; 1493 } 1494 return *ExpectedLineTable; 1495 } 1496 1497 Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit( 1498 DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) { 1499 return State->getLineTableForUnit(U, RecoverableErrorHandler); 1500 } 1501 1502 void DWARFContext::clearLineTableForUnit(DWARFUnit *U) { 1503 return State->clearLineTableForUnit(U); 1504 } 1505 1506 DWARFUnitVector &DWARFContext::getDWOUnits(bool Lazy) { 1507 return State->getDWOUnits(Lazy); 1508 } 1509 1510 DWARFUnit *DWARFContext::getUnitForOffset(uint64_t Offset) { 1511 return State->getNormalUnits().getUnitForOffset(Offset); 1512 } 1513 1514 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint64_t Offset) { 1515 return dyn_cast_or_null<DWARFCompileUnit>(getUnitForOffset(Offset)); 1516 } 1517 1518 DWARFCompileUnit *DWARFContext::getCompileUnitForCodeAddress(uint64_t Address) { 1519 uint64_t CUOffset = getDebugAranges()->findAddress(Address); 1520 return getCompileUnitForOffset(CUOffset); 1521 } 1522 1523 DWARFCompileUnit *DWARFContext::getCompileUnitForDataAddress(uint64_t Address) { 1524 uint64_t CUOffset = getDebugAranges()->findAddress(Address); 1525 if (DWARFCompileUnit *OffsetCU = getCompileUnitForOffset(CUOffset)) 1526 return OffsetCU; 1527 1528 // Global variables are often missed by the above search, for one of two 1529 // reasons: 1530 // 1. .debug_aranges may not include global variables. On clang, it seems we 1531 // put the globals in the aranges, but this isn't true for gcc. 1532 // 2. Even if the global variable is in a .debug_arange, global variables 1533 // may not be captured in the [start, end) addresses described by the 1534 // parent compile unit. 1535 // 1536 // So, we walk the CU's and their child DI's manually, looking for the 1537 // specific global variable. 1538 for (std::unique_ptr<DWARFUnit> &CU : compile_units()) { 1539 if (CU->getVariableForAddress(Address)) { 1540 return static_cast<DWARFCompileUnit *>(CU.get()); 1541 } 1542 } 1543 return nullptr; 1544 } 1545 1546 DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address, 1547 bool CheckDWO) { 1548 DIEsForAddress Result; 1549 1550 DWARFCompileUnit *CU = getCompileUnitForCodeAddress(Address); 1551 if (!CU) 1552 return Result; 1553 1554 if (CheckDWO) { 1555 // We were asked to check the DWO file and this debug information is more 1556 // complete that any information in the skeleton compile unit, so search the 1557 // DWO first to see if we have a match. 1558 DWARFDie CUDie = CU->getUnitDIE(false); 1559 DWARFDie CUDwoDie = CU->getNonSkeletonUnitDIE(false); 1560 if (CheckDWO && CUDwoDie && CUDie != CUDwoDie) { 1561 // We have a DWO file, lets search it. 1562 DWARFCompileUnit *CUDwo = 1563 dyn_cast_or_null<DWARFCompileUnit>(CUDwoDie.getDwarfUnit()); 1564 if (CUDwo) { 1565 Result.FunctionDIE = CUDwo->getSubroutineForAddress(Address); 1566 if (Result.FunctionDIE) 1567 Result.CompileUnit = CUDwo; 1568 } 1569 } 1570 } 1571 1572 // Search the normal DWARF if we didn't find a match in the DWO file or if 1573 // we didn't check the DWO file above. 1574 if (!Result) { 1575 Result.CompileUnit = CU; 1576 Result.FunctionDIE = CU->getSubroutineForAddress(Address); 1577 } 1578 1579 std::vector<DWARFDie> Worklist; 1580 Worklist.push_back(Result.FunctionDIE); 1581 while (!Worklist.empty()) { 1582 DWARFDie DIE = Worklist.back(); 1583 Worklist.pop_back(); 1584 1585 if (!DIE.isValid()) 1586 continue; 1587 1588 if (DIE.getTag() == DW_TAG_lexical_block && 1589 DIE.addressRangeContainsAddress(Address)) { 1590 Result.BlockDIE = DIE; 1591 break; 1592 } 1593 1594 append_range(Worklist, DIE); 1595 } 1596 1597 return Result; 1598 } 1599 1600 /// TODO: change input parameter from "uint64_t Address" 1601 /// into "SectionedAddress Address" 1602 static bool getFunctionNameAndStartLineForAddress( 1603 DWARFCompileUnit *CU, uint64_t Address, FunctionNameKind Kind, 1604 DILineInfoSpecifier::FileLineInfoKind FileNameKind, 1605 std::string &FunctionName, std::string &StartFile, uint32_t &StartLine, 1606 std::optional<uint64_t> &StartAddress) { 1607 // The address may correspond to instruction in some inlined function, 1608 // so we have to build the chain of inlined functions and take the 1609 // name of the topmost function in it. 1610 SmallVector<DWARFDie, 4> InlinedChain; 1611 CU->getInlinedChainForAddress(Address, InlinedChain); 1612 if (InlinedChain.empty()) 1613 return false; 1614 1615 const DWARFDie &DIE = InlinedChain[0]; 1616 bool FoundResult = false; 1617 const char *Name = nullptr; 1618 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) { 1619 FunctionName = Name; 1620 FoundResult = true; 1621 } 1622 std::string DeclFile = DIE.getDeclFile(FileNameKind); 1623 if (!DeclFile.empty()) { 1624 StartFile = DeclFile; 1625 FoundResult = true; 1626 } 1627 if (auto DeclLineResult = DIE.getDeclLine()) { 1628 StartLine = DeclLineResult; 1629 FoundResult = true; 1630 } 1631 if (auto LowPcAddr = toSectionedAddress(DIE.find(DW_AT_low_pc))) 1632 StartAddress = LowPcAddr->Address; 1633 return FoundResult; 1634 } 1635 1636 static std::optional<int64_t> 1637 getExpressionFrameOffset(ArrayRef<uint8_t> Expr, 1638 std::optional<unsigned> FrameBaseReg) { 1639 if (!Expr.empty() && 1640 (Expr[0] == DW_OP_fbreg || 1641 (FrameBaseReg && Expr[0] == DW_OP_breg0 + *FrameBaseReg))) { 1642 unsigned Count; 1643 int64_t Offset = decodeSLEB128(Expr.data() + 1, &Count, Expr.end()); 1644 // A single DW_OP_fbreg or DW_OP_breg. 1645 if (Expr.size() == Count + 1) 1646 return Offset; 1647 // Same + DW_OP_deref (Fortran arrays look like this). 1648 if (Expr.size() == Count + 2 && Expr[Count + 1] == DW_OP_deref) 1649 return Offset; 1650 // Fallthrough. Do not accept ex. (DW_OP_breg W29, DW_OP_stack_value) 1651 } 1652 return std::nullopt; 1653 } 1654 1655 void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram, 1656 DWARFDie Die, std::vector<DILocal> &Result) { 1657 if (Die.getTag() == DW_TAG_variable || 1658 Die.getTag() == DW_TAG_formal_parameter) { 1659 DILocal Local; 1660 if (const char *Name = Subprogram.getSubroutineName(DINameKind::ShortName)) 1661 Local.FunctionName = Name; 1662 1663 std::optional<unsigned> FrameBaseReg; 1664 if (auto FrameBase = Subprogram.find(DW_AT_frame_base)) 1665 if (std::optional<ArrayRef<uint8_t>> Expr = FrameBase->getAsBlock()) 1666 if (!Expr->empty() && (*Expr)[0] >= DW_OP_reg0 && 1667 (*Expr)[0] <= DW_OP_reg31) { 1668 FrameBaseReg = (*Expr)[0] - DW_OP_reg0; 1669 } 1670 1671 if (Expected<std::vector<DWARFLocationExpression>> Loc = 1672 Die.getLocations(DW_AT_location)) { 1673 for (const auto &Entry : *Loc) { 1674 if (std::optional<int64_t> FrameOffset = 1675 getExpressionFrameOffset(Entry.Expr, FrameBaseReg)) { 1676 Local.FrameOffset = *FrameOffset; 1677 break; 1678 } 1679 } 1680 } else { 1681 // FIXME: missing DW_AT_location is OK here, but other errors should be 1682 // reported to the user. 1683 consumeError(Loc.takeError()); 1684 } 1685 1686 if (auto TagOffsetAttr = Die.find(DW_AT_LLVM_tag_offset)) 1687 Local.TagOffset = TagOffsetAttr->getAsUnsignedConstant(); 1688 1689 if (auto Origin = 1690 Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin)) 1691 Die = Origin; 1692 if (auto NameAttr = Die.find(DW_AT_name)) 1693 if (std::optional<const char *> Name = dwarf::toString(*NameAttr)) 1694 Local.Name = *Name; 1695 if (auto Type = Die.getAttributeValueAsReferencedDie(DW_AT_type)) 1696 Local.Size = Type.getTypeSize(getCUAddrSize()); 1697 if (auto DeclFileAttr = Die.find(DW_AT_decl_file)) { 1698 if (const auto *LT = CU->getContext().getLineTableForUnit(CU)) 1699 LT->getFileNameByIndex( 1700 *DeclFileAttr->getAsUnsignedConstant(), CU->getCompilationDir(), 1701 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, 1702 Local.DeclFile); 1703 } 1704 if (auto DeclLineAttr = Die.find(DW_AT_decl_line)) 1705 Local.DeclLine = *DeclLineAttr->getAsUnsignedConstant(); 1706 1707 Result.push_back(Local); 1708 return; 1709 } 1710 1711 if (Die.getTag() == DW_TAG_inlined_subroutine) 1712 if (auto Origin = 1713 Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin)) 1714 Subprogram = Origin; 1715 1716 for (auto Child : Die) 1717 addLocalsForDie(CU, Subprogram, Child, Result); 1718 } 1719 1720 std::vector<DILocal> 1721 DWARFContext::getLocalsForAddress(object::SectionedAddress Address) { 1722 std::vector<DILocal> Result; 1723 DWARFCompileUnit *CU = getCompileUnitForCodeAddress(Address.Address); 1724 if (!CU) 1725 return Result; 1726 1727 DWARFDie Subprogram = CU->getSubroutineForAddress(Address.Address); 1728 if (Subprogram.isValid()) 1729 addLocalsForDie(CU, Subprogram, Subprogram, Result); 1730 return Result; 1731 } 1732 1733 DILineInfo DWARFContext::getLineInfoForAddress(object::SectionedAddress Address, 1734 DILineInfoSpecifier Spec) { 1735 DILineInfo Result; 1736 DWARFCompileUnit *CU = getCompileUnitForCodeAddress(Address.Address); 1737 if (!CU) 1738 return Result; 1739 1740 getFunctionNameAndStartLineForAddress( 1741 CU, Address.Address, Spec.FNKind, Spec.FLIKind, Result.FunctionName, 1742 Result.StartFileName, Result.StartLine, Result.StartAddress); 1743 if (Spec.FLIKind != FileLineInfoKind::None) { 1744 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU)) { 1745 LineTable->getFileLineInfoForAddress( 1746 {Address.Address, Address.SectionIndex}, Spec.ApproximateLine, 1747 CU->getCompilationDir(), Spec.FLIKind, Result); 1748 } 1749 } 1750 1751 return Result; 1752 } 1753 1754 DILineInfo 1755 DWARFContext::getLineInfoForDataAddress(object::SectionedAddress Address) { 1756 DILineInfo Result; 1757 DWARFCompileUnit *CU = getCompileUnitForDataAddress(Address.Address); 1758 if (!CU) 1759 return Result; 1760 1761 if (DWARFDie Die = CU->getVariableForAddress(Address.Address)) { 1762 Result.FileName = Die.getDeclFile(FileLineInfoKind::AbsoluteFilePath); 1763 Result.Line = Die.getDeclLine(); 1764 } 1765 1766 return Result; 1767 } 1768 1769 DILineInfoTable DWARFContext::getLineInfoForAddressRange( 1770 object::SectionedAddress Address, uint64_t Size, DILineInfoSpecifier Spec) { 1771 DILineInfoTable Lines; 1772 DWARFCompileUnit *CU = getCompileUnitForCodeAddress(Address.Address); 1773 if (!CU) 1774 return Lines; 1775 1776 uint32_t StartLine = 0; 1777 std::string StartFileName; 1778 std::string FunctionName(DILineInfo::BadString); 1779 std::optional<uint64_t> StartAddress; 1780 getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind, 1781 Spec.FLIKind, FunctionName, 1782 StartFileName, StartLine, StartAddress); 1783 1784 // If the Specifier says we don't need FileLineInfo, just 1785 // return the top-most function at the starting address. 1786 if (Spec.FLIKind == FileLineInfoKind::None) { 1787 DILineInfo Result; 1788 Result.FunctionName = FunctionName; 1789 Result.StartFileName = StartFileName; 1790 Result.StartLine = StartLine; 1791 Result.StartAddress = StartAddress; 1792 Lines.push_back(std::make_pair(Address.Address, Result)); 1793 return Lines; 1794 } 1795 1796 const DWARFLineTable *LineTable = getLineTableForUnit(CU); 1797 1798 // Get the index of row we're looking for in the line table. 1799 std::vector<uint32_t> RowVector; 1800 if (!LineTable->lookupAddressRange({Address.Address, Address.SectionIndex}, 1801 Size, RowVector)) { 1802 return Lines; 1803 } 1804 1805 for (uint32_t RowIndex : RowVector) { 1806 // Take file number and line/column from the row. 1807 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex]; 1808 DILineInfo Result; 1809 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(), 1810 Spec.FLIKind, Result.FileName); 1811 Result.FunctionName = FunctionName; 1812 Result.Line = Row.Line; 1813 Result.Column = Row.Column; 1814 Result.StartFileName = StartFileName; 1815 Result.StartLine = StartLine; 1816 Result.StartAddress = StartAddress; 1817 Lines.push_back(std::make_pair(Row.Address.Address, Result)); 1818 } 1819 1820 return Lines; 1821 } 1822 1823 DIInliningInfo 1824 DWARFContext::getInliningInfoForAddress(object::SectionedAddress Address, 1825 DILineInfoSpecifier Spec) { 1826 DIInliningInfo InliningInfo; 1827 1828 DWARFCompileUnit *CU = getCompileUnitForCodeAddress(Address.Address); 1829 if (!CU) 1830 return InliningInfo; 1831 1832 const DWARFLineTable *LineTable = nullptr; 1833 SmallVector<DWARFDie, 4> InlinedChain; 1834 CU->getInlinedChainForAddress(Address.Address, InlinedChain); 1835 if (InlinedChain.size() == 0) { 1836 // If there is no DIE for address (e.g. it is in unavailable .dwo file), 1837 // try to at least get file/line info from symbol table. 1838 if (Spec.FLIKind != FileLineInfoKind::None) { 1839 DILineInfo Frame; 1840 LineTable = getLineTableForUnit(CU); 1841 if (LineTable && 1842 LineTable->getFileLineInfoForAddress( 1843 {Address.Address, Address.SectionIndex}, Spec.ApproximateLine, 1844 CU->getCompilationDir(), Spec.FLIKind, Frame)) 1845 InliningInfo.addFrame(Frame); 1846 } 1847 return InliningInfo; 1848 } 1849 1850 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0; 1851 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) { 1852 DWARFDie &FunctionDIE = InlinedChain[i]; 1853 DILineInfo Frame; 1854 // Get function name if necessary. 1855 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind)) 1856 Frame.FunctionName = Name; 1857 if (auto DeclLineResult = FunctionDIE.getDeclLine()) 1858 Frame.StartLine = DeclLineResult; 1859 Frame.StartFileName = FunctionDIE.getDeclFile(Spec.FLIKind); 1860 if (auto LowPcAddr = toSectionedAddress(FunctionDIE.find(DW_AT_low_pc))) 1861 Frame.StartAddress = LowPcAddr->Address; 1862 if (Spec.FLIKind != FileLineInfoKind::None) { 1863 if (i == 0) { 1864 // For the topmost frame, initialize the line table of this 1865 // compile unit and fetch file/line info from it. 1866 LineTable = getLineTableForUnit(CU); 1867 // For the topmost routine, get file/line info from line table. 1868 if (LineTable) 1869 LineTable->getFileLineInfoForAddress( 1870 {Address.Address, Address.SectionIndex}, Spec.ApproximateLine, 1871 CU->getCompilationDir(), Spec.FLIKind, Frame); 1872 } else { 1873 // Otherwise, use call file, call line and call column from 1874 // previous DIE in inlined chain. 1875 if (LineTable) 1876 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(), 1877 Spec.FLIKind, Frame.FileName); 1878 Frame.Line = CallLine; 1879 Frame.Column = CallColumn; 1880 Frame.Discriminator = CallDiscriminator; 1881 } 1882 // Get call file/line/column of a current DIE. 1883 if (i + 1 < n) { 1884 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn, 1885 CallDiscriminator); 1886 } 1887 } 1888 InliningInfo.addFrame(Frame); 1889 } 1890 return InliningInfo; 1891 } 1892 1893 std::shared_ptr<DWARFContext> 1894 DWARFContext::getDWOContext(StringRef AbsolutePath) { 1895 return State->getDWOContext(AbsolutePath); 1896 } 1897 1898 static Error createError(const Twine &Reason, llvm::Error E) { 1899 return make_error<StringError>(Reason + toString(std::move(E)), 1900 inconvertibleErrorCode()); 1901 } 1902 1903 /// SymInfo contains information about symbol: it's address 1904 /// and section index which is -1LL for absolute symbols. 1905 struct SymInfo { 1906 uint64_t Address; 1907 uint64_t SectionIndex; 1908 }; 1909 1910 /// Returns the address of symbol relocation used against and a section index. 1911 /// Used for futher relocations computation. Symbol's section load address is 1912 static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj, 1913 const RelocationRef &Reloc, 1914 const LoadedObjectInfo *L, 1915 std::map<SymbolRef, SymInfo> &Cache) { 1916 SymInfo Ret = {0, (uint64_t)-1LL}; 1917 object::section_iterator RSec = Obj.section_end(); 1918 object::symbol_iterator Sym = Reloc.getSymbol(); 1919 1920 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end(); 1921 // First calculate the address of the symbol or section as it appears 1922 // in the object file 1923 if (Sym != Obj.symbol_end()) { 1924 bool New; 1925 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}}); 1926 if (!New) 1927 return CacheIt->second; 1928 1929 Expected<uint64_t> SymAddrOrErr = Sym->getAddress(); 1930 if (!SymAddrOrErr) 1931 return createError("failed to compute symbol address: ", 1932 SymAddrOrErr.takeError()); 1933 1934 // Also remember what section this symbol is in for later 1935 auto SectOrErr = Sym->getSection(); 1936 if (!SectOrErr) 1937 return createError("failed to get symbol section: ", 1938 SectOrErr.takeError()); 1939 1940 RSec = *SectOrErr; 1941 Ret.Address = *SymAddrOrErr; 1942 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) { 1943 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl()); 1944 Ret.Address = RSec->getAddress(); 1945 } 1946 1947 if (RSec != Obj.section_end()) 1948 Ret.SectionIndex = RSec->getIndex(); 1949 1950 // If we are given load addresses for the sections, we need to adjust: 1951 // SymAddr = (Address of Symbol Or Section in File) - 1952 // (Address of Section in File) + 1953 // (Load Address of Section) 1954 // RSec is now either the section being targeted or the section 1955 // containing the symbol being targeted. In either case, 1956 // we need to perform the same computation. 1957 if (L && RSec != Obj.section_end()) 1958 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec)) 1959 Ret.Address += SectionLoadAddress - RSec->getAddress(); 1960 1961 if (CacheIt != Cache.end()) 1962 CacheIt->second = Ret; 1963 1964 return Ret; 1965 } 1966 1967 static bool isRelocScattered(const object::ObjectFile &Obj, 1968 const RelocationRef &Reloc) { 1969 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj); 1970 if (!MachObj) 1971 return false; 1972 // MachO also has relocations that point to sections and 1973 // scattered relocations. 1974 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl()); 1975 return MachObj->isRelocationScattered(RelocInfo); 1976 } 1977 1978 namespace { 1979 struct DWARFSectionMap final : public DWARFSection { 1980 RelocAddrMap Relocs; 1981 }; 1982 1983 class DWARFObjInMemory final : public DWARFObject { 1984 bool IsLittleEndian; 1985 uint8_t AddressSize; 1986 StringRef FileName; 1987 const object::ObjectFile *Obj = nullptr; 1988 std::vector<SectionName> SectionNames; 1989 1990 using InfoSectionMap = MapVector<object::SectionRef, DWARFSectionMap, 1991 std::map<object::SectionRef, unsigned>>; 1992 1993 InfoSectionMap InfoSections; 1994 InfoSectionMap TypesSections; 1995 InfoSectionMap InfoDWOSections; 1996 InfoSectionMap TypesDWOSections; 1997 1998 DWARFSectionMap LocSection; 1999 DWARFSectionMap LoclistsSection; 2000 DWARFSectionMap LoclistsDWOSection; 2001 DWARFSectionMap LineSection; 2002 DWARFSectionMap RangesSection; 2003 DWARFSectionMap RnglistsSection; 2004 DWARFSectionMap StrOffsetsSection; 2005 DWARFSectionMap LineDWOSection; 2006 DWARFSectionMap FrameSection; 2007 DWARFSectionMap EHFrameSection; 2008 DWARFSectionMap LocDWOSection; 2009 DWARFSectionMap StrOffsetsDWOSection; 2010 DWARFSectionMap RangesDWOSection; 2011 DWARFSectionMap RnglistsDWOSection; 2012 DWARFSectionMap AddrSection; 2013 DWARFSectionMap AppleNamesSection; 2014 DWARFSectionMap AppleTypesSection; 2015 DWARFSectionMap AppleNamespacesSection; 2016 DWARFSectionMap AppleObjCSection; 2017 DWARFSectionMap NamesSection; 2018 DWARFSectionMap PubnamesSection; 2019 DWARFSectionMap PubtypesSection; 2020 DWARFSectionMap GnuPubnamesSection; 2021 DWARFSectionMap GnuPubtypesSection; 2022 DWARFSectionMap MacroSection; 2023 2024 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) { 2025 return StringSwitch<DWARFSectionMap *>(Name) 2026 .Case("debug_loc", &LocSection) 2027 .Case("debug_loclists", &LoclistsSection) 2028 .Case("debug_loclists.dwo", &LoclistsDWOSection) 2029 .Case("debug_line", &LineSection) 2030 .Case("debug_frame", &FrameSection) 2031 .Case("eh_frame", &EHFrameSection) 2032 .Case("debug_str_offsets", &StrOffsetsSection) 2033 .Case("debug_ranges", &RangesSection) 2034 .Case("debug_rnglists", &RnglistsSection) 2035 .Case("debug_loc.dwo", &LocDWOSection) 2036 .Case("debug_line.dwo", &LineDWOSection) 2037 .Case("debug_names", &NamesSection) 2038 .Case("debug_rnglists.dwo", &RnglistsDWOSection) 2039 .Case("debug_str_offsets.dwo", &StrOffsetsDWOSection) 2040 .Case("debug_addr", &AddrSection) 2041 .Case("apple_names", &AppleNamesSection) 2042 .Case("debug_pubnames", &PubnamesSection) 2043 .Case("debug_pubtypes", &PubtypesSection) 2044 .Case("debug_gnu_pubnames", &GnuPubnamesSection) 2045 .Case("debug_gnu_pubtypes", &GnuPubtypesSection) 2046 .Case("apple_types", &AppleTypesSection) 2047 .Case("apple_namespaces", &AppleNamespacesSection) 2048 .Case("apple_namespac", &AppleNamespacesSection) 2049 .Case("apple_objc", &AppleObjCSection) 2050 .Case("debug_macro", &MacroSection) 2051 .Default(nullptr); 2052 } 2053 2054 StringRef AbbrevSection; 2055 StringRef ArangesSection; 2056 StringRef StrSection; 2057 StringRef MacinfoSection; 2058 StringRef MacinfoDWOSection; 2059 StringRef MacroDWOSection; 2060 StringRef AbbrevDWOSection; 2061 StringRef StrDWOSection; 2062 StringRef CUIndexSection; 2063 StringRef GdbIndexSection; 2064 StringRef TUIndexSection; 2065 StringRef LineStrSection; 2066 2067 // A deque holding section data whose iterators are not invalidated when 2068 // new decompressed sections are inserted at the end. 2069 std::deque<SmallString<0>> UncompressedSections; 2070 2071 StringRef *mapSectionToMember(StringRef Name) { 2072 if (DWARFSection *Sec = mapNameToDWARFSection(Name)) 2073 return &Sec->Data; 2074 return StringSwitch<StringRef *>(Name) 2075 .Case("debug_abbrev", &AbbrevSection) 2076 .Case("debug_aranges", &ArangesSection) 2077 .Case("debug_str", &StrSection) 2078 .Case("debug_macinfo", &MacinfoSection) 2079 .Case("debug_macinfo.dwo", &MacinfoDWOSection) 2080 .Case("debug_macro.dwo", &MacroDWOSection) 2081 .Case("debug_abbrev.dwo", &AbbrevDWOSection) 2082 .Case("debug_str.dwo", &StrDWOSection) 2083 .Case("debug_cu_index", &CUIndexSection) 2084 .Case("debug_tu_index", &TUIndexSection) 2085 .Case("gdb_index", &GdbIndexSection) 2086 .Case("debug_line_str", &LineStrSection) 2087 // Any more debug info sections go here. 2088 .Default(nullptr); 2089 } 2090 2091 /// If Sec is compressed section, decompresses and updates its contents 2092 /// provided by Data. Otherwise leaves it unchanged. 2093 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name, 2094 StringRef &Data) { 2095 if (!Sec.isCompressed()) 2096 return Error::success(); 2097 2098 Expected<Decompressor> Decompressor = 2099 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8); 2100 if (!Decompressor) 2101 return Decompressor.takeError(); 2102 2103 SmallString<0> Out; 2104 if (auto Err = Decompressor->resizeAndDecompress(Out)) 2105 return Err; 2106 2107 UncompressedSections.push_back(std::move(Out)); 2108 Data = UncompressedSections.back(); 2109 2110 return Error::success(); 2111 } 2112 2113 public: 2114 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections, 2115 uint8_t AddrSize, bool IsLittleEndian) 2116 : IsLittleEndian(IsLittleEndian) { 2117 for (const auto &SecIt : Sections) { 2118 if (StringRef *SectionData = mapSectionToMember(SecIt.first())) 2119 *SectionData = SecIt.second->getBuffer(); 2120 else if (SecIt.first() == "debug_info") 2121 // Find debug_info and debug_types data by section rather than name as 2122 // there are multiple, comdat grouped, of these sections. 2123 InfoSections[SectionRef()].Data = SecIt.second->getBuffer(); 2124 else if (SecIt.first() == "debug_info.dwo") 2125 InfoDWOSections[SectionRef()].Data = SecIt.second->getBuffer(); 2126 else if (SecIt.first() == "debug_types") 2127 TypesSections[SectionRef()].Data = SecIt.second->getBuffer(); 2128 else if (SecIt.first() == "debug_types.dwo") 2129 TypesDWOSections[SectionRef()].Data = SecIt.second->getBuffer(); 2130 } 2131 } 2132 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L, 2133 function_ref<void(Error)> HandleError, 2134 function_ref<void(Error)> HandleWarning, 2135 DWARFContext::ProcessDebugRelocations RelocAction) 2136 : IsLittleEndian(Obj.isLittleEndian()), 2137 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()), 2138 Obj(&Obj) { 2139 2140 StringMap<unsigned> SectionAmountMap; 2141 for (const SectionRef &Section : Obj.sections()) { 2142 StringRef Name; 2143 if (auto NameOrErr = Section.getName()) 2144 Name = *NameOrErr; 2145 else 2146 consumeError(NameOrErr.takeError()); 2147 2148 ++SectionAmountMap[Name]; 2149 SectionNames.push_back({ Name, true }); 2150 2151 // Skip BSS and Virtual sections, they aren't interesting. 2152 if (Section.isBSS() || Section.isVirtual()) 2153 continue; 2154 2155 // Skip sections stripped by dsymutil. 2156 if (Section.isStripped()) 2157 continue; 2158 2159 StringRef Data; 2160 Expected<section_iterator> SecOrErr = Section.getRelocatedSection(); 2161 if (!SecOrErr) { 2162 HandleError(createError("failed to get relocated section: ", 2163 SecOrErr.takeError())); 2164 continue; 2165 } 2166 2167 // Try to obtain an already relocated version of this section. 2168 // Else use the unrelocated section from the object file. We'll have to 2169 // apply relocations ourselves later. 2170 section_iterator RelocatedSection = 2171 Obj.isRelocatableObject() ? *SecOrErr : Obj.section_end(); 2172 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data)) { 2173 Expected<StringRef> E = Section.getContents(); 2174 if (E) 2175 Data = *E; 2176 else 2177 // maybeDecompress below will error. 2178 consumeError(E.takeError()); 2179 } 2180 2181 if (auto Err = maybeDecompress(Section, Name, Data)) { 2182 HandleError(createError("failed to decompress '" + Name + "', ", 2183 std::move(Err))); 2184 continue; 2185 } 2186 2187 // Map platform specific debug section names to DWARF standard section 2188 // names. 2189 Name = Name.substr(Name.find_first_not_of("._")); 2190 Name = Obj.mapDebugSectionName(Name); 2191 2192 if (StringRef *SectionData = mapSectionToMember(Name)) { 2193 *SectionData = Data; 2194 if (Name == "debug_ranges") { 2195 // FIXME: Use the other dwo range section when we emit it. 2196 RangesDWOSection.Data = Data; 2197 } else if (Name == "debug_frame" || Name == "eh_frame") { 2198 if (DWARFSection *S = mapNameToDWARFSection(Name)) 2199 S->Address = Section.getAddress(); 2200 } 2201 } else if (InfoSectionMap *Sections = 2202 StringSwitch<InfoSectionMap *>(Name) 2203 .Case("debug_info", &InfoSections) 2204 .Case("debug_info.dwo", &InfoDWOSections) 2205 .Case("debug_types", &TypesSections) 2206 .Case("debug_types.dwo", &TypesDWOSections) 2207 .Default(nullptr)) { 2208 // Find debug_info and debug_types data by section rather than name as 2209 // there are multiple, comdat grouped, of these sections. 2210 DWARFSectionMap &S = (*Sections)[Section]; 2211 S.Data = Data; 2212 } 2213 2214 if (RelocatedSection == Obj.section_end() || 2215 (RelocAction == DWARFContext::ProcessDebugRelocations::Ignore)) 2216 continue; 2217 2218 StringRef RelSecName; 2219 if (auto NameOrErr = RelocatedSection->getName()) 2220 RelSecName = *NameOrErr; 2221 else 2222 consumeError(NameOrErr.takeError()); 2223 2224 // If the section we're relocating was relocated already by the JIT, 2225 // then we used the relocated version above, so we do not need to process 2226 // relocations for it now. 2227 StringRef RelSecData; 2228 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData)) 2229 continue; 2230 2231 // In Mach-o files, the relocations do not need to be applied if 2232 // there is no load offset to apply. The value read at the 2233 // relocation point already factors in the section address 2234 // (actually applying the relocations will produce wrong results 2235 // as the section address will be added twice). 2236 if (!L && isa<MachOObjectFile>(&Obj)) 2237 continue; 2238 2239 if (!Section.relocations().empty() && Name.ends_with(".dwo") && 2240 RelSecName.starts_with(".debug")) { 2241 HandleWarning(createError("unexpected relocations for dwo section '" + 2242 RelSecName + "'")); 2243 } 2244 2245 // TODO: Add support for relocations in other sections as needed. 2246 // Record relocations for the debug_info and debug_line sections. 2247 RelSecName = RelSecName.substr(RelSecName.find_first_not_of("._")); 2248 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName); 2249 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr; 2250 if (!Map) { 2251 // Find debug_info and debug_types relocs by section rather than name 2252 // as there are multiple, comdat grouped, of these sections. 2253 if (RelSecName == "debug_info") 2254 Map = &static_cast<DWARFSectionMap &>(InfoSections[*RelocatedSection]) 2255 .Relocs; 2256 else if (RelSecName == "debug_types") 2257 Map = 2258 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection]) 2259 .Relocs; 2260 else 2261 continue; 2262 } 2263 2264 if (Section.relocation_begin() == Section.relocation_end()) 2265 continue; 2266 2267 // Symbol to [address, section index] cache mapping. 2268 std::map<SymbolRef, SymInfo> AddrCache; 2269 SupportsRelocation Supports; 2270 RelocationResolver Resolver; 2271 std::tie(Supports, Resolver) = getRelocationResolver(Obj); 2272 for (const RelocationRef &Reloc : Section.relocations()) { 2273 // FIXME: it's not clear how to correctly handle scattered 2274 // relocations. 2275 if (isRelocScattered(Obj, Reloc)) 2276 continue; 2277 2278 Expected<SymInfo> SymInfoOrErr = 2279 getSymbolInfo(Obj, Reloc, L, AddrCache); 2280 if (!SymInfoOrErr) { 2281 HandleError(SymInfoOrErr.takeError()); 2282 continue; 2283 } 2284 2285 // Check if Resolver can handle this relocation type early so as not to 2286 // handle invalid cases in DWARFDataExtractor. 2287 // 2288 // TODO Don't store Resolver in every RelocAddrEntry. 2289 if (Supports && Supports(Reloc.getType())) { 2290 auto I = Map->try_emplace( 2291 Reloc.getOffset(), 2292 RelocAddrEntry{ 2293 SymInfoOrErr->SectionIndex, Reloc, SymInfoOrErr->Address, 2294 std::optional<object::RelocationRef>(), 0, Resolver}); 2295 // If we didn't successfully insert that's because we already had a 2296 // relocation for that offset. Store it as a second relocation in the 2297 // same RelocAddrEntry instead. 2298 if (!I.second) { 2299 RelocAddrEntry &entry = I.first->getSecond(); 2300 if (entry.Reloc2) { 2301 HandleError(createError( 2302 "At most two relocations per offset are supported")); 2303 } 2304 entry.Reloc2 = Reloc; 2305 entry.SymbolValue2 = SymInfoOrErr->Address; 2306 } 2307 } else { 2308 SmallString<32> Type; 2309 Reloc.getTypeName(Type); 2310 // FIXME: Support more relocations & change this to an error 2311 HandleWarning( 2312 createError("failed to compute relocation: " + Type + ", ", 2313 errorCodeToError(object_error::parse_failed))); 2314 } 2315 } 2316 } 2317 2318 for (SectionName &S : SectionNames) 2319 if (SectionAmountMap[S.Name] > 1) 2320 S.IsNameUnique = false; 2321 } 2322 2323 std::optional<RelocAddrEntry> find(const DWARFSection &S, 2324 uint64_t Pos) const override { 2325 auto &Sec = static_cast<const DWARFSectionMap &>(S); 2326 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos); 2327 if (AI == Sec.Relocs.end()) 2328 return std::nullopt; 2329 return AI->second; 2330 } 2331 2332 const object::ObjectFile *getFile() const override { return Obj; } 2333 2334 ArrayRef<SectionName> getSectionNames() const override { 2335 return SectionNames; 2336 } 2337 2338 bool isLittleEndian() const override { return IsLittleEndian; } 2339 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; } 2340 const DWARFSection &getLineDWOSection() const override { 2341 return LineDWOSection; 2342 } 2343 const DWARFSection &getLocDWOSection() const override { 2344 return LocDWOSection; 2345 } 2346 StringRef getStrDWOSection() const override { return StrDWOSection; } 2347 const DWARFSection &getStrOffsetsDWOSection() const override { 2348 return StrOffsetsDWOSection; 2349 } 2350 const DWARFSection &getRangesDWOSection() const override { 2351 return RangesDWOSection; 2352 } 2353 const DWARFSection &getRnglistsDWOSection() const override { 2354 return RnglistsDWOSection; 2355 } 2356 const DWARFSection &getLoclistsDWOSection() const override { 2357 return LoclistsDWOSection; 2358 } 2359 const DWARFSection &getAddrSection() const override { return AddrSection; } 2360 StringRef getCUIndexSection() const override { return CUIndexSection; } 2361 StringRef getGdbIndexSection() const override { return GdbIndexSection; } 2362 StringRef getTUIndexSection() const override { return TUIndexSection; } 2363 2364 // DWARF v5 2365 const DWARFSection &getStrOffsetsSection() const override { 2366 return StrOffsetsSection; 2367 } 2368 StringRef getLineStrSection() const override { return LineStrSection; } 2369 2370 // Sections for DWARF5 split dwarf proposal. 2371 void forEachInfoDWOSections( 2372 function_ref<void(const DWARFSection &)> F) const override { 2373 for (auto &P : InfoDWOSections) 2374 F(P.second); 2375 } 2376 void forEachTypesDWOSections( 2377 function_ref<void(const DWARFSection &)> F) const override { 2378 for (auto &P : TypesDWOSections) 2379 F(P.second); 2380 } 2381 2382 StringRef getAbbrevSection() const override { return AbbrevSection; } 2383 const DWARFSection &getLocSection() const override { return LocSection; } 2384 const DWARFSection &getLoclistsSection() const override { return LoclistsSection; } 2385 StringRef getArangesSection() const override { return ArangesSection; } 2386 const DWARFSection &getFrameSection() const override { 2387 return FrameSection; 2388 } 2389 const DWARFSection &getEHFrameSection() const override { 2390 return EHFrameSection; 2391 } 2392 const DWARFSection &getLineSection() const override { return LineSection; } 2393 StringRef getStrSection() const override { return StrSection; } 2394 const DWARFSection &getRangesSection() const override { return RangesSection; } 2395 const DWARFSection &getRnglistsSection() const override { 2396 return RnglistsSection; 2397 } 2398 const DWARFSection &getMacroSection() const override { return MacroSection; } 2399 StringRef getMacroDWOSection() const override { return MacroDWOSection; } 2400 StringRef getMacinfoSection() const override { return MacinfoSection; } 2401 StringRef getMacinfoDWOSection() const override { return MacinfoDWOSection; } 2402 const DWARFSection &getPubnamesSection() const override { return PubnamesSection; } 2403 const DWARFSection &getPubtypesSection() const override { return PubtypesSection; } 2404 const DWARFSection &getGnuPubnamesSection() const override { 2405 return GnuPubnamesSection; 2406 } 2407 const DWARFSection &getGnuPubtypesSection() const override { 2408 return GnuPubtypesSection; 2409 } 2410 const DWARFSection &getAppleNamesSection() const override { 2411 return AppleNamesSection; 2412 } 2413 const DWARFSection &getAppleTypesSection() const override { 2414 return AppleTypesSection; 2415 } 2416 const DWARFSection &getAppleNamespacesSection() const override { 2417 return AppleNamespacesSection; 2418 } 2419 const DWARFSection &getAppleObjCSection() const override { 2420 return AppleObjCSection; 2421 } 2422 const DWARFSection &getNamesSection() const override { 2423 return NamesSection; 2424 } 2425 2426 StringRef getFileName() const override { return FileName; } 2427 uint8_t getAddressSize() const override { return AddressSize; } 2428 void forEachInfoSections( 2429 function_ref<void(const DWARFSection &)> F) const override { 2430 for (auto &P : InfoSections) 2431 F(P.second); 2432 } 2433 void forEachTypesSections( 2434 function_ref<void(const DWARFSection &)> F) const override { 2435 for (auto &P : TypesSections) 2436 F(P.second); 2437 } 2438 }; 2439 } // namespace 2440 2441 std::unique_ptr<DWARFContext> 2442 DWARFContext::create(const object::ObjectFile &Obj, 2443 ProcessDebugRelocations RelocAction, 2444 const LoadedObjectInfo *L, std::string DWPName, 2445 std::function<void(Error)> RecoverableErrorHandler, 2446 std::function<void(Error)> WarningHandler, 2447 bool ThreadSafe) { 2448 auto DObj = std::make_unique<DWARFObjInMemory>( 2449 Obj, L, RecoverableErrorHandler, WarningHandler, RelocAction); 2450 return std::make_unique<DWARFContext>(std::move(DObj), 2451 std::move(DWPName), 2452 RecoverableErrorHandler, 2453 WarningHandler, 2454 ThreadSafe); 2455 } 2456 2457 std::unique_ptr<DWARFContext> 2458 DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections, 2459 uint8_t AddrSize, bool isLittleEndian, 2460 std::function<void(Error)> RecoverableErrorHandler, 2461 std::function<void(Error)> WarningHandler, 2462 bool ThreadSafe) { 2463 auto DObj = 2464 std::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian); 2465 return std::make_unique<DWARFContext>( 2466 std::move(DObj), "", RecoverableErrorHandler, WarningHandler, ThreadSafe); 2467 } 2468 2469 uint8_t DWARFContext::getCUAddrSize() { 2470 // In theory, different compile units may have different address byte 2471 // sizes, but for simplicity we just use the address byte size of the 2472 // first compile unit. In practice the address size field is repeated across 2473 // various DWARF headers (at least in version 5) to make it easier to dump 2474 // them independently, not to enable varying the address size. 2475 auto CUs = compile_units(); 2476 return CUs.empty() ? 0 : (*CUs.begin())->getAddressByteSize(); 2477 } 2478 2479 bool DWARFContext::isDWP() const { return !DObj->getCUIndexSection().empty(); } 2480