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