1 //===- DWARFContext.cpp ---------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/DebugInfo/DWARF/DWARFContext.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/DWARFDebugAbbrev.h" 20 #include "llvm/DebugInfo/DWARF/DWARFDebugAddr.h" 21 #include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h" 22 #include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h" 23 #include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h" 24 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h" 25 #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h" 26 #include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h" 27 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.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/RelocVisitor.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/MemoryBuffer.h" 45 #include "llvm/Support/Path.h" 46 #include "llvm/Support/TargetRegistry.h" 47 #include "llvm/Support/WithColor.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 : DIContext(CK_DWARF), DWPName(std::move(DWPName)), DObj(std::move(DObj)) {} 70 71 DWARFContext::~DWARFContext() = default; 72 73 /// Dump the UUID load command. 74 static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) { 75 auto *MachO = dyn_cast<MachOObjectFile>(&Obj); 76 if (!MachO) 77 return; 78 for (auto LC : MachO->load_commands()) { 79 raw_ostream::uuid_t UUID; 80 if (LC.C.cmd == MachO::LC_UUID) { 81 if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) { 82 OS << "error: UUID load command is too short.\n"; 83 return; 84 } 85 OS << "UUID: "; 86 memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID)); 87 OS.write_uuid(UUID); 88 Triple T = MachO->getArchTriple(); 89 OS << " (" << T.getArchName() << ')'; 90 OS << ' ' << MachO->getFileName() << '\n'; 91 } 92 } 93 } 94 95 using ContributionCollection = 96 std::vector<Optional<StrOffsetsContributionDescriptor>>; 97 98 // Collect all the contributions to the string offsets table from all units, 99 // sort them by their starting offsets and remove duplicates. 100 static ContributionCollection 101 collectContributionData(DWARFContext::unit_iterator_range Units) { 102 ContributionCollection Contributions; 103 for (const auto &U : Units) 104 Contributions.push_back(U->getStringOffsetsTableContribution()); 105 // Sort the contributions so that any invalid ones are placed at 106 // the start of the contributions vector. This way they are reported 107 // first. 108 llvm::sort(Contributions, 109 [](const Optional<StrOffsetsContributionDescriptor> &L, 110 const Optional<StrOffsetsContributionDescriptor> &R) { 111 if (L && R) 112 return L->Base < R->Base; 113 return R.hasValue(); 114 }); 115 116 // Uniquify contributions, as it is possible that units (specifically 117 // type units in dwo or dwp files) share contributions. We don't want 118 // to report them more than once. 119 Contributions.erase( 120 std::unique(Contributions.begin(), Contributions.end(), 121 [](const Optional<StrOffsetsContributionDescriptor> &L, 122 const Optional<StrOffsetsContributionDescriptor> &R) { 123 if (L && R) 124 return L->Base == R->Base && L->Size == R->Size; 125 return false; 126 }), 127 Contributions.end()); 128 return Contributions; 129 } 130 131 static void dumpDWARFv5StringOffsetsSection( 132 raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj, 133 const DWARFSection &StringOffsetsSection, StringRef StringSection, 134 DWARFContext::unit_iterator_range Units, bool LittleEndian) { 135 auto Contributions = collectContributionData(Units); 136 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0); 137 DataExtractor StrData(StringSection, LittleEndian, 0); 138 uint64_t SectionSize = StringOffsetsSection.Data.size(); 139 uint32_t Offset = 0; 140 for (auto &Contribution : Contributions) { 141 // Report an ill-formed contribution. 142 if (!Contribution) { 143 OS << "error: invalid contribution to string offsets table in section ." 144 << SectionName << ".\n"; 145 return; 146 } 147 148 dwarf::DwarfFormat Format = Contribution->getFormat(); 149 uint16_t Version = Contribution->getVersion(); 150 uint64_t ContributionHeader = Contribution->Base; 151 // In DWARF v5 there is a contribution header that immediately precedes 152 // the string offsets base (the location we have previously retrieved from 153 // the CU DIE's DW_AT_str_offsets attribute). The header is located either 154 // 8 or 16 bytes before the base, depending on the contribution's format. 155 if (Version >= 5) 156 ContributionHeader -= Format == DWARF32 ? 8 : 16; 157 158 // Detect overlapping contributions. 159 if (Offset > ContributionHeader) { 160 OS << "error: overlapping contributions to string offsets table in " 161 "section ." 162 << SectionName << ".\n"; 163 return; 164 } 165 // Report a gap in the table. 166 if (Offset < ContributionHeader) { 167 OS << format("0x%8.8x: Gap, length = ", Offset); 168 OS << (ContributionHeader - Offset) << "\n"; 169 } 170 OS << format("0x%8.8x: ", (uint32_t)ContributionHeader); 171 // In DWARF v5 the contribution size in the descriptor does not equal 172 // the originally encoded length (it does not contain the length of the 173 // version field and the padding, a total of 4 bytes). Add them back in 174 // for reporting. 175 OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 0 : 4)) 176 << ", Format = " << (Format == DWARF32 ? "DWARF32" : "DWARF64") 177 << ", Version = " << Version << "\n"; 178 179 Offset = Contribution->Base; 180 unsigned EntrySize = Contribution->getDwarfOffsetByteSize(); 181 while (Offset - Contribution->Base < Contribution->Size) { 182 OS << format("0x%8.8x: ", Offset); 183 // FIXME: We can only extract strings if the offset fits in 32 bits. 184 uint64_t StringOffset = 185 StrOffsetExt.getRelocatedValue(EntrySize, &Offset); 186 // Extract the string if we can and display it. Otherwise just report 187 // the offset. 188 if (StringOffset <= std::numeric_limits<uint32_t>::max()) { 189 uint32_t StringOffset32 = (uint32_t)StringOffset; 190 OS << format("%8.8x ", StringOffset32); 191 const char *S = StrData.getCStr(&StringOffset32); 192 if (S) 193 OS << format("\"%s\"", S); 194 } else 195 OS << format("%16.16" PRIx64 " ", StringOffset); 196 OS << "\n"; 197 } 198 } 199 // Report a gap at the end of the table. 200 if (Offset < SectionSize) { 201 OS << format("0x%8.8x: Gap, length = ", Offset); 202 OS << (SectionSize - Offset) << "\n"; 203 } 204 } 205 206 // Dump a DWARF string offsets section. This may be a DWARF v5 formatted 207 // string offsets section, where each compile or type unit contributes a 208 // number of entries (string offsets), with each contribution preceded by 209 // a header containing size and version number. Alternatively, it may be a 210 // monolithic series of string offsets, as generated by the pre-DWARF v5 211 // implementation of split DWARF. 212 static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName, 213 const DWARFObject &Obj, 214 const DWARFSection &StringOffsetsSection, 215 StringRef StringSection, 216 DWARFContext::unit_iterator_range Units, 217 bool LittleEndian, unsigned MaxVersion) { 218 // If we have at least one (compile or type) unit with DWARF v5 or greater, 219 // we assume that the section is formatted like a DWARF v5 string offsets 220 // section. 221 if (MaxVersion >= 5) 222 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection, 223 StringSection, Units, LittleEndian); 224 else { 225 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0); 226 uint32_t offset = 0; 227 uint64_t size = StringOffsetsSection.Data.size(); 228 // Ensure that size is a multiple of the size of an entry. 229 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) { 230 OS << "error: size of ." << SectionName << " is not a multiple of " 231 << sizeof(uint32_t) << ".\n"; 232 size &= -(uint64_t)sizeof(uint32_t); 233 } 234 DataExtractor StrData(StringSection, LittleEndian, 0); 235 while (offset < size) { 236 OS << format("0x%8.8x: ", offset); 237 uint32_t StringOffset = strOffsetExt.getU32(&offset); 238 OS << format("%8.8x ", StringOffset); 239 const char *S = StrData.getCStr(&StringOffset); 240 if (S) 241 OS << format("\"%s\"", S); 242 OS << "\n"; 243 } 244 } 245 } 246 247 // Dump the .debug_addr section. 248 static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData, 249 DIDumpOptions DumpOpts, uint16_t Version, 250 uint8_t AddrSize) { 251 uint32_t Offset = 0; 252 while (AddrData.isValidOffset(Offset)) { 253 DWARFDebugAddrTable AddrTable; 254 uint32_t TableOffset = Offset; 255 if (Error Err = AddrTable.extract(AddrData, &Offset, Version, AddrSize, 256 DWARFContext::dumpWarning)) { 257 WithColor::error() << toString(std::move(Err)) << '\n'; 258 // Keep going after an error, if we can, assuming that the length field 259 // could be read. If it couldn't, stop reading the section. 260 if (!AddrTable.hasValidLength()) 261 break; 262 uint64_t Length = AddrTable.getLength(); 263 Offset = TableOffset + Length; 264 } else { 265 AddrTable.dump(OS, DumpOpts); 266 } 267 } 268 } 269 270 // Dump a section that contains a sequence of tables of lists, such as range 271 // or location list tables. In DWARF v5 we expect to find properly formatted 272 // tables with headers. In DWARF v4 and earlier we simply expect a sequence of 273 // lists, which we treat, mutatis mutandis, like DWARF v5 tables. 274 template <typename ListTable> 275 static void 276 dumpListSection(raw_ostream &OS, DWARFContext *C, StringRef SectionName, 277 uint16_t MaxVersion, DWARFDataExtractor &ListData, 278 llvm::function_ref<Optional<SectionedAddress>(uint32_t)> 279 LookupPooledAddress, 280 DIDumpOptions DumpOpts, bool isDWO = false) { 281 uint32_t Offset = 0; 282 while (ListData.isValidOffset(Offset)) { 283 ListTable Table(C, SectionName, isDWO); 284 if (Error Err = Table.extract(ListData, MaxVersion, &Offset)) { 285 WithColor::error() << toString(std::move(Err)) << '\n'; 286 // If table extraction set Offset to 0, it indicates that we cannot 287 // continue to read the section. 288 if (Offset == 0) 289 break; 290 // In DWARF v4 and earlier, dump as much of the lists as we can. 291 if (MaxVersion < 5) 292 Table.dump(OS, LookupPooledAddress, DumpOpts); 293 } else { 294 Table.dump(OS, LookupPooledAddress, DumpOpts); 295 } 296 } 297 } 298 299 static void dumpLoclistsSection(raw_ostream &OS, DIDumpOptions DumpOpts, 300 DWARFDataExtractor Data, 301 const MCRegisterInfo *MRI, 302 Optional<uint64_t> DumpOffset) { 303 uint32_t Offset = 0; 304 DWARFDebugLoclists Loclists; 305 306 DWARFListTableHeader Header(".debug_loclists", "locations"); 307 if (Error E = Header.extract(Data, &Offset)) { 308 WithColor::error() << toString(std::move(E)) << '\n'; 309 return; 310 } 311 312 Header.dump(OS, DumpOpts); 313 DataExtractor LocData(Data.getData().drop_front(Offset), 314 Data.isLittleEndian(), Header.getAddrSize()); 315 316 Loclists.parse(LocData, Header.getVersion()); 317 Loclists.dump(OS, 0, MRI, DumpOffset); 318 } 319 320 void DWARFContext::dump( 321 raw_ostream &OS, DIDumpOptions DumpOpts, 322 std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) { 323 324 Optional<uint64_t> DumpOffset; 325 uint64_t DumpType = DumpOpts.DumpType; 326 327 StringRef Extension = sys::path::extension(DObj->getFileName()); 328 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp"); 329 330 // Print UUID header. 331 const auto *ObjFile = DObj->getFile(); 332 if (DumpType & DIDT_UUID) 333 dumpUUID(OS, *ObjFile); 334 335 // Print a header for each explicitly-requested section. 336 // Otherwise just print one for non-empty sections. 337 // Only print empty .dwo section headers when dumping a .dwo file. 338 bool Explicit = DumpType != DIDT_All && !IsDWO; 339 bool ExplicitDWO = Explicit && IsDWO; 340 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID, 341 StringRef Section) { 342 DumpOffset = DumpOffsets[ID]; 343 unsigned Mask = 1U << ID; 344 bool Should = (DumpType & Mask) && (Explicit || !Section.empty()); 345 if (Should) 346 OS << "\n" << Name << " contents:\n"; 347 return Should; 348 }; 349 350 // Dump individual sections. 351 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev, 352 DObj->getAbbrevSection())) 353 getDebugAbbrev()->dump(OS); 354 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev, 355 DObj->getAbbrevDWOSection())) 356 getDebugAbbrevDWO()->dump(OS); 357 358 auto dumpDebugInfo = [&](unit_iterator_range Units) { 359 if (DumpOffset) 360 getDIEForOffset(DumpOffset.getValue()) 361 .dump(OS, 0, DumpOpts.noImplicitRecursion()); 362 else 363 for (const auto &U : Units) 364 U->dump(OS, DumpOpts); 365 }; 366 if (shouldDump(Explicit, ".debug_info", DIDT_ID_DebugInfo, 367 DObj->getInfoSection().Data)) 368 dumpDebugInfo(info_section_units()); 369 if (shouldDump(ExplicitDWO, ".debug_info.dwo", DIDT_ID_DebugInfo, 370 DObj->getInfoDWOSection().Data)) 371 dumpDebugInfo(dwo_info_section_units()); 372 373 auto dumpDebugType = [&](const char *Name, unit_iterator_range Units) { 374 OS << '\n' << Name << " contents:\n"; 375 DumpOffset = DumpOffsets[DIDT_ID_DebugTypes]; 376 for (const auto &U : Units) 377 if (DumpOffset) 378 U->getDIEForOffset(*DumpOffset) 379 .dump(OS, 0, DumpOpts.noImplicitRecursion()); 380 else 381 U->dump(OS, DumpOpts); 382 }; 383 if ((DumpType & DIDT_DebugTypes)) { 384 if (Explicit || getNumTypeUnits()) 385 dumpDebugType(".debug_types", types_section_units()); 386 if (ExplicitDWO || getNumDWOTypeUnits()) 387 dumpDebugType(".debug_types.dwo", dwo_types_section_units()); 388 } 389 390 if (shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc, 391 DObj->getLocSection().Data)) { 392 getDebugLoc()->dump(OS, getRegisterInfo(), DumpOffset); 393 } 394 if (shouldDump(Explicit, ".debug_loclists", DIDT_ID_DebugLoclists, 395 DObj->getLoclistsSection().Data)) { 396 DWARFDataExtractor Data(*DObj, DObj->getLoclistsSection(), isLittleEndian(), 397 0); 398 dumpLoclistsSection(OS, DumpOpts, Data, getRegisterInfo(), DumpOffset); 399 } 400 if (shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc, 401 DObj->getLocDWOSection().Data)) { 402 getDebugLocDWO()->dump(OS, 0, getRegisterInfo(), DumpOffset); 403 } 404 405 if (shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame, 406 DObj->getDebugFrameSection())) 407 getDebugFrame()->dump(OS, getRegisterInfo(), DumpOffset); 408 409 if (shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame, 410 DObj->getEHFrameSection())) 411 getEHFrame()->dump(OS, getRegisterInfo(), DumpOffset); 412 413 if (DumpType & DIDT_DebugMacro) { 414 if (Explicit || !getDebugMacro()->empty()) { 415 OS << "\n.debug_macinfo contents:\n"; 416 getDebugMacro()->dump(OS); 417 } 418 } 419 420 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges, 421 DObj->getARangeSection())) { 422 uint32_t offset = 0; 423 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0); 424 DWARFDebugArangeSet set; 425 while (set.extract(arangesData, &offset)) 426 set.dump(OS); 427 } 428 429 auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser, 430 DIDumpOptions DumpOpts) { 431 while (!Parser.done()) { 432 if (DumpOffset && Parser.getOffset() != *DumpOffset) { 433 Parser.skip(dumpWarning); 434 continue; 435 } 436 OS << "debug_line[" << format("0x%8.8x", Parser.getOffset()) << "]\n"; 437 if (DumpOpts.Verbose) { 438 Parser.parseNext(dumpWarning, dumpWarning, &OS); 439 } else { 440 DWARFDebugLine::LineTable LineTable = 441 Parser.parseNext(dumpWarning, dumpWarning); 442 LineTable.dump(OS, DumpOpts); 443 } 444 } 445 }; 446 447 if (shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine, 448 DObj->getLineSection().Data)) { 449 DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(), 450 0); 451 DWARFDebugLine::SectionParser Parser(LineData, *this, compile_units(), 452 type_units()); 453 DumpLineSection(Parser, DumpOpts); 454 } 455 456 if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine, 457 DObj->getLineDWOSection().Data)) { 458 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(), 459 isLittleEndian(), 0); 460 DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_compile_units(), 461 dwo_type_units()); 462 DumpLineSection(Parser, DumpOpts); 463 } 464 465 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex, 466 DObj->getCUIndexSection())) { 467 getCUIndex().dump(OS); 468 } 469 470 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex, 471 DObj->getTUIndexSection())) { 472 getTUIndex().dump(OS); 473 } 474 475 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr, 476 DObj->getStringSection())) { 477 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0); 478 uint32_t offset = 0; 479 uint32_t strOffset = 0; 480 while (const char *s = strData.getCStr(&offset)) { 481 OS << format("0x%8.8x: \"%s\"\n", strOffset, s); 482 strOffset = offset; 483 } 484 } 485 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr, 486 DObj->getStringDWOSection())) { 487 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0); 488 uint32_t offset = 0; 489 uint32_t strDWOOffset = 0; 490 while (const char *s = strDWOData.getCStr(&offset)) { 491 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s); 492 strDWOOffset = offset; 493 } 494 } 495 if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr, 496 DObj->getLineStringSection())) { 497 DataExtractor strData(DObj->getLineStringSection(), isLittleEndian(), 0); 498 uint32_t offset = 0; 499 uint32_t strOffset = 0; 500 while (const char *s = strData.getCStr(&offset)) { 501 OS << format("0x%8.8x: \"", strOffset); 502 OS.write_escaped(s); 503 OS << "\"\n"; 504 strOffset = offset; 505 } 506 } 507 508 if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr, 509 DObj->getAddrSection().Data)) { 510 DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(), 511 isLittleEndian(), 0); 512 dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize()); 513 } 514 515 auto LookupPooledAddress = [&](uint32_t Index) -> Optional<SectionedAddress> { 516 const auto &CUs = compile_units(); 517 auto I = CUs.begin(); 518 if (I == CUs.end()) 519 return None; 520 return (*I)->getAddrOffsetSectionItem(Index); 521 }; 522 523 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges, 524 DObj->getRangeSection().Data)) { 525 uint8_t savedAddressByteSize = getCUAddrSize(); 526 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(), 527 isLittleEndian(), savedAddressByteSize); 528 dumpListSection<DWARFDebugRnglistTable>(OS, this, ".debug_ranges", 529 /* MaxVersion = */ 4, rangesData, 530 LookupPooledAddress, DumpOpts); 531 } 532 533 if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists, 534 DObj->getRnglistsSection().Data)) { 535 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(), 536 isLittleEndian(), getCUAddrSize()); 537 dumpListSection<DWARFDebugRnglistTable>(OS, this, ".debug_rnglists", 538 getMaxVersion(5), RnglistData, 539 LookupPooledAddress, DumpOpts); 540 } 541 542 if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists, 543 DObj->getRnglistsDWOSection().Data)) { 544 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(), 545 isLittleEndian(), getCUAddrSize()); 546 dumpListSection<DWARFDebugRnglistTable>(OS, this, ".debug_rnglists.dwo", 547 getMaxVersion(5), RnglistData, 548 LookupPooledAddress, DumpOpts); 549 } 550 551 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames, 552 DObj->getPubNamesSection())) 553 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false) 554 .dump(OS); 555 556 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes, 557 DObj->getPubTypesSection())) 558 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false) 559 .dump(OS); 560 561 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames, 562 DObj->getGnuPubNamesSection())) 563 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(), 564 true /* GnuStyle */) 565 .dump(OS); 566 567 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes, 568 DObj->getGnuPubTypesSection())) 569 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(), 570 true /* GnuStyle */) 571 .dump(OS); 572 573 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets, 574 DObj->getStringOffsetSection().Data)) 575 dumpStringOffsetsSection(OS, "debug_str_offsets", *DObj, 576 DObj->getStringOffsetSection(), 577 DObj->getStringSection(), normal_units(), 578 isLittleEndian(), getMaxVersion()); 579 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets, 580 DObj->getStringOffsetDWOSection().Data)) 581 dumpStringOffsetsSection(OS, "debug_str_offsets.dwo", *DObj, 582 DObj->getStringOffsetDWOSection(), 583 DObj->getStringDWOSection(), dwo_units(), 584 isLittleEndian(), getMaxDWOVersion()); 585 586 if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex, 587 DObj->getGdbIndexSection())) { 588 getGdbIndex().dump(OS); 589 } 590 591 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames, 592 DObj->getAppleNamesSection().Data)) 593 getAppleNames().dump(OS); 594 595 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes, 596 DObj->getAppleTypesSection().Data)) 597 getAppleTypes().dump(OS); 598 599 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces, 600 DObj->getAppleNamespacesSection().Data)) 601 getAppleNamespaces().dump(OS); 602 603 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC, 604 DObj->getAppleObjCSection().Data)) 605 getAppleObjC().dump(OS); 606 if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames, 607 DObj->getDebugNamesSection().Data)) 608 getDebugNames().dump(OS); 609 } 610 611 DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) { 612 parseDWOUnits(LazyParse); 613 614 if (const auto &CUI = getCUIndex()) { 615 if (const auto *R = CUI.getFromHash(Hash)) 616 return dyn_cast_or_null<DWARFCompileUnit>( 617 DWOUnits.getUnitForIndexEntry(*R)); 618 return nullptr; 619 } 620 621 // If there's no index, just search through the CUs in the DWO - there's 622 // probably only one unless this is something like LTO - though an in-process 623 // built/cached lookup table could be used in that case to improve repeated 624 // lookups of different CUs in the DWO. 625 for (const auto &DWOCU : dwo_compile_units()) { 626 // Might not have parsed DWO ID yet. 627 if (!DWOCU->getDWOId()) { 628 if (Optional<uint64_t> DWOId = 629 toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id))) 630 DWOCU->setDWOId(*DWOId); 631 else 632 // No DWO ID? 633 continue; 634 } 635 if (DWOCU->getDWOId() == Hash) 636 return dyn_cast<DWARFCompileUnit>(DWOCU.get()); 637 } 638 return nullptr; 639 } 640 641 DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) { 642 parseNormalUnits(); 643 if (auto *CU = NormalUnits.getUnitForOffset(Offset)) 644 return CU->getDIEForOffset(Offset); 645 return DWARFDie(); 646 } 647 648 bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) { 649 bool Success = true; 650 DWARFVerifier verifier(OS, *this, DumpOpts); 651 652 Success &= verifier.handleDebugAbbrev(); 653 if (DumpOpts.DumpType & DIDT_DebugInfo) 654 Success &= verifier.handleDebugInfo(); 655 if (DumpOpts.DumpType & DIDT_DebugLine) 656 Success &= verifier.handleDebugLine(); 657 Success &= verifier.handleAccelTables(); 658 return Success; 659 } 660 661 const DWARFUnitIndex &DWARFContext::getCUIndex() { 662 if (CUIndex) 663 return *CUIndex; 664 665 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0); 666 667 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO); 668 CUIndex->parse(CUIndexData); 669 return *CUIndex; 670 } 671 672 const DWARFUnitIndex &DWARFContext::getTUIndex() { 673 if (TUIndex) 674 return *TUIndex; 675 676 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0); 677 678 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES); 679 TUIndex->parse(TUIndexData); 680 return *TUIndex; 681 } 682 683 DWARFGdbIndex &DWARFContext::getGdbIndex() { 684 if (GdbIndex) 685 return *GdbIndex; 686 687 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0); 688 GdbIndex = llvm::make_unique<DWARFGdbIndex>(); 689 GdbIndex->parse(GdbIndexData); 690 return *GdbIndex; 691 } 692 693 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() { 694 if (Abbrev) 695 return Abbrev.get(); 696 697 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0); 698 699 Abbrev.reset(new DWARFDebugAbbrev()); 700 Abbrev->extract(abbrData); 701 return Abbrev.get(); 702 } 703 704 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() { 705 if (AbbrevDWO) 706 return AbbrevDWO.get(); 707 708 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0); 709 AbbrevDWO.reset(new DWARFDebugAbbrev()); 710 AbbrevDWO->extract(abbrData); 711 return AbbrevDWO.get(); 712 } 713 714 const DWARFDebugLoc *DWARFContext::getDebugLoc() { 715 if (Loc) 716 return Loc.get(); 717 718 Loc.reset(new DWARFDebugLoc); 719 // Assume all units have the same address byte size. 720 if (getNumCompileUnits()) { 721 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(), 722 getUnitAtIndex(0)->getAddressByteSize()); 723 Loc->parse(LocData); 724 } 725 return Loc.get(); 726 } 727 728 const DWARFDebugLoclists *DWARFContext::getDebugLocDWO() { 729 if (LocDWO) 730 return LocDWO.get(); 731 732 LocDWO.reset(new DWARFDebugLoclists()); 733 // Assume all compile units have the same address byte size. 734 // FIXME: We don't need AddressSize for split DWARF since relocatable 735 // addresses cannot appear there. At the moment DWARFExpression requires it. 736 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 4); 737 // Use version 4. DWO does not support the DWARF v5 .debug_loclists yet and 738 // that means we are parsing the new style .debug_loc (pre-standatized version 739 // of the .debug_loclists). 740 LocDWO->parse(LocData, 4 /* Version */); 741 return LocDWO.get(); 742 } 743 744 const DWARFDebugAranges *DWARFContext::getDebugAranges() { 745 if (Aranges) 746 return Aranges.get(); 747 748 Aranges.reset(new DWARFDebugAranges()); 749 Aranges->generate(this); 750 return Aranges.get(); 751 } 752 753 const DWARFDebugFrame *DWARFContext::getDebugFrame() { 754 if (DebugFrame) 755 return DebugFrame.get(); 756 757 // There's a "bug" in the DWARFv3 standard with respect to the target address 758 // size within debug frame sections. While DWARF is supposed to be independent 759 // of its container, FDEs have fields with size being "target address size", 760 // which isn't specified in DWARF in general. It's only specified for CUs, but 761 // .eh_frame can appear without a .debug_info section. Follow the example of 762 // other tools (libdwarf) and extract this from the container (ObjectFile 763 // provides this information). This problem is fixed in DWARFv4 764 // See this dwarf-discuss discussion for more details: 765 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html 766 DWARFDataExtractor debugFrameData(DObj->getDebugFrameSection(), 767 isLittleEndian(), DObj->getAddressSize()); 768 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */)); 769 DebugFrame->parse(debugFrameData); 770 return DebugFrame.get(); 771 } 772 773 const DWARFDebugFrame *DWARFContext::getEHFrame() { 774 if (EHFrame) 775 return EHFrame.get(); 776 777 DWARFDataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(), 778 DObj->getAddressSize()); 779 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */)); 780 DebugFrame->parse(debugFrameData); 781 return DebugFrame.get(); 782 } 783 784 const DWARFDebugMacro *DWARFContext::getDebugMacro() { 785 if (Macro) 786 return Macro.get(); 787 788 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0); 789 Macro.reset(new DWARFDebugMacro()); 790 Macro->parse(MacinfoData); 791 return Macro.get(); 792 } 793 794 template <typename T> 795 static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj, 796 const DWARFSection &Section, StringRef StringSection, 797 bool IsLittleEndian) { 798 if (Cache) 799 return *Cache; 800 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0); 801 DataExtractor StrData(StringSection, IsLittleEndian, 0); 802 Cache.reset(new T(AccelSection, StrData)); 803 if (Error E = Cache->extract()) 804 llvm::consumeError(std::move(E)); 805 return *Cache; 806 } 807 808 const DWARFDebugNames &DWARFContext::getDebugNames() { 809 return getAccelTable(Names, *DObj, DObj->getDebugNamesSection(), 810 DObj->getStringSection(), isLittleEndian()); 811 } 812 813 const AppleAcceleratorTable &DWARFContext::getAppleNames() { 814 return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(), 815 DObj->getStringSection(), isLittleEndian()); 816 } 817 818 const AppleAcceleratorTable &DWARFContext::getAppleTypes() { 819 return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(), 820 DObj->getStringSection(), isLittleEndian()); 821 } 822 823 const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() { 824 return getAccelTable(AppleNamespaces, *DObj, 825 DObj->getAppleNamespacesSection(), 826 DObj->getStringSection(), isLittleEndian()); 827 } 828 829 const AppleAcceleratorTable &DWARFContext::getAppleObjC() { 830 return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(), 831 DObj->getStringSection(), isLittleEndian()); 832 } 833 834 const DWARFDebugLine::LineTable * 835 DWARFContext::getLineTableForUnit(DWARFUnit *U) { 836 Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable = 837 getLineTableForUnit(U, dumpWarning); 838 if (!ExpectedLineTable) { 839 dumpWarning(ExpectedLineTable.takeError()); 840 return nullptr; 841 } 842 return *ExpectedLineTable; 843 } 844 845 Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit( 846 DWARFUnit *U, std::function<void(Error)> RecoverableErrorCallback) { 847 if (!Line) 848 Line.reset(new DWARFDebugLine); 849 850 auto UnitDIE = U->getUnitDIE(); 851 if (!UnitDIE) 852 return nullptr; 853 854 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list)); 855 if (!Offset) 856 return nullptr; // No line table for this compile unit. 857 858 uint32_t stmtOffset = *Offset + U->getLineTableOffset(); 859 // See if the line table is cached. 860 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset)) 861 return lt; 862 863 // Make sure the offset is good before we try to parse. 864 if (stmtOffset >= U->getLineSection().Data.size()) 865 return nullptr; 866 867 // We have to parse it first. 868 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(), 869 U->getAddressByteSize()); 870 return Line->getOrParseLineTable(lineData, stmtOffset, *this, U, 871 RecoverableErrorCallback); 872 } 873 874 void DWARFContext::parseNormalUnits() { 875 if (!NormalUnits.empty()) 876 return; 877 NormalUnits.addUnitsForSection(*this, DObj->getInfoSection(), DW_SECT_INFO); 878 NormalUnits.finishedInfoUnits(); 879 DObj->forEachTypesSections([&](const DWARFSection &S) { 880 NormalUnits.addUnitsForSection(*this, S, DW_SECT_TYPES); 881 }); 882 } 883 884 void DWARFContext::parseDWOUnits(bool Lazy) { 885 if (!DWOUnits.empty()) 886 return; 887 DWOUnits.addUnitsForDWOSection(*this, DObj->getInfoDWOSection(), DW_SECT_INFO, 888 Lazy); 889 DWOUnits.finishedInfoUnits(); 890 DObj->forEachTypesDWOSections([&](const DWARFSection &S) { 891 DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_TYPES, Lazy); 892 }); 893 } 894 895 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) { 896 parseNormalUnits(); 897 return dyn_cast_or_null<DWARFCompileUnit>( 898 NormalUnits.getUnitForOffset(Offset)); 899 } 900 901 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) { 902 // First, get the offset of the compile unit. 903 uint32_t CUOffset = getDebugAranges()->findAddress(Address); 904 // Retrieve the compile unit. 905 return getCompileUnitForOffset(CUOffset); 906 } 907 908 DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) { 909 DIEsForAddress Result; 910 911 DWARFCompileUnit *CU = getCompileUnitForAddress(Address); 912 if (!CU) 913 return Result; 914 915 Result.CompileUnit = CU; 916 Result.FunctionDIE = CU->getSubroutineForAddress(Address); 917 918 std::vector<DWARFDie> Worklist; 919 Worklist.push_back(Result.FunctionDIE); 920 while (!Worklist.empty()) { 921 DWARFDie DIE = Worklist.back(); 922 Worklist.pop_back(); 923 924 if (DIE.getTag() == DW_TAG_lexical_block && 925 DIE.addressRangeContainsAddress(Address)) { 926 Result.BlockDIE = DIE; 927 break; 928 } 929 930 for (auto Child : DIE) 931 Worklist.push_back(Child); 932 } 933 934 return Result; 935 } 936 937 static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU, 938 uint64_t Address, 939 FunctionNameKind Kind, 940 std::string &FunctionName, 941 uint32_t &StartLine) { 942 // The address may correspond to instruction in some inlined function, 943 // so we have to build the chain of inlined functions and take the 944 // name of the topmost function in it. 945 SmallVector<DWARFDie, 4> InlinedChain; 946 CU->getInlinedChainForAddress(Address, InlinedChain); 947 if (InlinedChain.empty()) 948 return false; 949 950 const DWARFDie &DIE = InlinedChain[0]; 951 bool FoundResult = false; 952 const char *Name = nullptr; 953 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) { 954 FunctionName = Name; 955 FoundResult = true; 956 } 957 if (auto DeclLineResult = DIE.getDeclLine()) { 958 StartLine = DeclLineResult; 959 FoundResult = true; 960 } 961 962 return FoundResult; 963 } 964 965 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address, 966 DILineInfoSpecifier Spec) { 967 DILineInfo Result; 968 969 DWARFCompileUnit *CU = getCompileUnitForAddress(Address); 970 if (!CU) 971 return Result; 972 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, 973 Result.FunctionName, 974 Result.StartLine); 975 if (Spec.FLIKind != FileLineInfoKind::None) { 976 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU)) 977 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(), 978 Spec.FLIKind, Result); 979 } 980 return Result; 981 } 982 983 DILineInfoTable 984 DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size, 985 DILineInfoSpecifier Spec) { 986 DILineInfoTable Lines; 987 DWARFCompileUnit *CU = getCompileUnitForAddress(Address); 988 if (!CU) 989 return Lines; 990 991 std::string FunctionName = "<invalid>"; 992 uint32_t StartLine = 0; 993 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName, 994 StartLine); 995 996 // If the Specifier says we don't need FileLineInfo, just 997 // return the top-most function at the starting address. 998 if (Spec.FLIKind == FileLineInfoKind::None) { 999 DILineInfo Result; 1000 Result.FunctionName = FunctionName; 1001 Result.StartLine = StartLine; 1002 Lines.push_back(std::make_pair(Address, Result)); 1003 return Lines; 1004 } 1005 1006 const DWARFLineTable *LineTable = getLineTableForUnit(CU); 1007 1008 // Get the index of row we're looking for in the line table. 1009 std::vector<uint32_t> RowVector; 1010 if (!LineTable->lookupAddressRange(Address, Size, RowVector)) 1011 return Lines; 1012 1013 for (uint32_t RowIndex : RowVector) { 1014 // Take file number and line/column from the row. 1015 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex]; 1016 DILineInfo Result; 1017 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(), 1018 Spec.FLIKind, Result.FileName); 1019 Result.FunctionName = FunctionName; 1020 Result.Line = Row.Line; 1021 Result.Column = Row.Column; 1022 Result.StartLine = StartLine; 1023 Lines.push_back(std::make_pair(Row.Address, Result)); 1024 } 1025 1026 return Lines; 1027 } 1028 1029 DIInliningInfo 1030 DWARFContext::getInliningInfoForAddress(uint64_t Address, 1031 DILineInfoSpecifier Spec) { 1032 DIInliningInfo InliningInfo; 1033 1034 DWARFCompileUnit *CU = getCompileUnitForAddress(Address); 1035 if (!CU) 1036 return InliningInfo; 1037 1038 const DWARFLineTable *LineTable = nullptr; 1039 SmallVector<DWARFDie, 4> InlinedChain; 1040 CU->getInlinedChainForAddress(Address, InlinedChain); 1041 if (InlinedChain.size() == 0) { 1042 // If there is no DIE for address (e.g. it is in unavailable .dwo file), 1043 // try to at least get file/line info from symbol table. 1044 if (Spec.FLIKind != FileLineInfoKind::None) { 1045 DILineInfo Frame; 1046 LineTable = getLineTableForUnit(CU); 1047 if (LineTable && 1048 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(), 1049 Spec.FLIKind, Frame)) 1050 InliningInfo.addFrame(Frame); 1051 } 1052 return InliningInfo; 1053 } 1054 1055 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0; 1056 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) { 1057 DWARFDie &FunctionDIE = InlinedChain[i]; 1058 DILineInfo Frame; 1059 // Get function name if necessary. 1060 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind)) 1061 Frame.FunctionName = Name; 1062 if (auto DeclLineResult = FunctionDIE.getDeclLine()) 1063 Frame.StartLine = DeclLineResult; 1064 if (Spec.FLIKind != FileLineInfoKind::None) { 1065 if (i == 0) { 1066 // For the topmost frame, initialize the line table of this 1067 // compile unit and fetch file/line info from it. 1068 LineTable = getLineTableForUnit(CU); 1069 // For the topmost routine, get file/line info from line table. 1070 if (LineTable) 1071 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(), 1072 Spec.FLIKind, Frame); 1073 } else { 1074 // Otherwise, use call file, call line and call column from 1075 // previous DIE in inlined chain. 1076 if (LineTable) 1077 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(), 1078 Spec.FLIKind, Frame.FileName); 1079 Frame.Line = CallLine; 1080 Frame.Column = CallColumn; 1081 Frame.Discriminator = CallDiscriminator; 1082 } 1083 // Get call file/line/column of a current DIE. 1084 if (i + 1 < n) { 1085 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn, 1086 CallDiscriminator); 1087 } 1088 } 1089 InliningInfo.addFrame(Frame); 1090 } 1091 return InliningInfo; 1092 } 1093 1094 std::shared_ptr<DWARFContext> 1095 DWARFContext::getDWOContext(StringRef AbsolutePath) { 1096 if (auto S = DWP.lock()) { 1097 DWARFContext *Ctxt = S->Context.get(); 1098 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt); 1099 } 1100 1101 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath]; 1102 1103 if (auto S = Entry->lock()) { 1104 DWARFContext *Ctxt = S->Context.get(); 1105 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt); 1106 } 1107 1108 Expected<OwningBinary<ObjectFile>> Obj = [&] { 1109 if (!CheckedForDWP) { 1110 SmallString<128> DWPName; 1111 auto Obj = object::ObjectFile::createObjectFile( 1112 this->DWPName.empty() 1113 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName) 1114 : StringRef(this->DWPName)); 1115 if (Obj) { 1116 Entry = &DWP; 1117 return Obj; 1118 } else { 1119 CheckedForDWP = true; 1120 // TODO: Should this error be handled (maybe in a high verbosity mode) 1121 // before falling back to .dwo files? 1122 consumeError(Obj.takeError()); 1123 } 1124 } 1125 1126 return object::ObjectFile::createObjectFile(AbsolutePath); 1127 }(); 1128 1129 if (!Obj) { 1130 // TODO: Actually report errors helpfully. 1131 consumeError(Obj.takeError()); 1132 return nullptr; 1133 } 1134 1135 auto S = std::make_shared<DWOFile>(); 1136 S->File = std::move(Obj.get()); 1137 S->Context = DWARFContext::create(*S->File.getBinary()); 1138 *Entry = S; 1139 auto *Ctxt = S->Context.get(); 1140 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt); 1141 } 1142 1143 static Error createError(const Twine &Reason, llvm::Error E) { 1144 return make_error<StringError>(Reason + toString(std::move(E)), 1145 inconvertibleErrorCode()); 1146 } 1147 1148 /// SymInfo contains information about symbol: it's address 1149 /// and section index which is -1LL for absolute symbols. 1150 struct SymInfo { 1151 uint64_t Address; 1152 uint64_t SectionIndex; 1153 }; 1154 1155 /// Returns the address of symbol relocation used against and a section index. 1156 /// Used for futher relocations computation. Symbol's section load address is 1157 static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj, 1158 const RelocationRef &Reloc, 1159 const LoadedObjectInfo *L, 1160 std::map<SymbolRef, SymInfo> &Cache) { 1161 SymInfo Ret = {0, (uint64_t)-1LL}; 1162 object::section_iterator RSec = Obj.section_end(); 1163 object::symbol_iterator Sym = Reloc.getSymbol(); 1164 1165 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end(); 1166 // First calculate the address of the symbol or section as it appears 1167 // in the object file 1168 if (Sym != Obj.symbol_end()) { 1169 bool New; 1170 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}}); 1171 if (!New) 1172 return CacheIt->second; 1173 1174 Expected<uint64_t> SymAddrOrErr = Sym->getAddress(); 1175 if (!SymAddrOrErr) 1176 return createError("failed to compute symbol address: ", 1177 SymAddrOrErr.takeError()); 1178 1179 // Also remember what section this symbol is in for later 1180 auto SectOrErr = Sym->getSection(); 1181 if (!SectOrErr) 1182 return createError("failed to get symbol section: ", 1183 SectOrErr.takeError()); 1184 1185 RSec = *SectOrErr; 1186 Ret.Address = *SymAddrOrErr; 1187 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) { 1188 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl()); 1189 Ret.Address = RSec->getAddress(); 1190 } 1191 1192 if (RSec != Obj.section_end()) 1193 Ret.SectionIndex = RSec->getIndex(); 1194 1195 // If we are given load addresses for the sections, we need to adjust: 1196 // SymAddr = (Address of Symbol Or Section in File) - 1197 // (Address of Section in File) + 1198 // (Load Address of Section) 1199 // RSec is now either the section being targeted or the section 1200 // containing the symbol being targeted. In either case, 1201 // we need to perform the same computation. 1202 if (L && RSec != Obj.section_end()) 1203 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec)) 1204 Ret.Address += SectionLoadAddress - RSec->getAddress(); 1205 1206 if (CacheIt != Cache.end()) 1207 CacheIt->second = Ret; 1208 1209 return Ret; 1210 } 1211 1212 static bool isRelocScattered(const object::ObjectFile &Obj, 1213 const RelocationRef &Reloc) { 1214 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj); 1215 if (!MachObj) 1216 return false; 1217 // MachO also has relocations that point to sections and 1218 // scattered relocations. 1219 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl()); 1220 return MachObj->isRelocationScattered(RelocInfo); 1221 } 1222 1223 ErrorPolicy DWARFContext::defaultErrorHandler(Error E) { 1224 WithColor::error() << toString(std::move(E)) << '\n'; 1225 return ErrorPolicy::Continue; 1226 } 1227 1228 namespace { 1229 struct DWARFSectionMap final : public DWARFSection { 1230 RelocAddrMap Relocs; 1231 }; 1232 1233 class DWARFObjInMemory final : public DWARFObject { 1234 bool IsLittleEndian; 1235 uint8_t AddressSize; 1236 StringRef FileName; 1237 const object::ObjectFile *Obj = nullptr; 1238 std::vector<SectionName> SectionNames; 1239 1240 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap, 1241 std::map<object::SectionRef, unsigned>>; 1242 1243 TypeSectionMap TypesSections; 1244 TypeSectionMap TypesDWOSections; 1245 1246 DWARFSectionMap InfoSection; 1247 DWARFSectionMap LocSection; 1248 DWARFSectionMap LocListsSection; 1249 DWARFSectionMap LineSection; 1250 DWARFSectionMap RangeSection; 1251 DWARFSectionMap RnglistsSection; 1252 DWARFSectionMap StringOffsetSection; 1253 DWARFSectionMap InfoDWOSection; 1254 DWARFSectionMap LineDWOSection; 1255 DWARFSectionMap LocDWOSection; 1256 DWARFSectionMap StringOffsetDWOSection; 1257 DWARFSectionMap RangeDWOSection; 1258 DWARFSectionMap RnglistsDWOSection; 1259 DWARFSectionMap AddrSection; 1260 DWARFSectionMap AppleNamesSection; 1261 DWARFSectionMap AppleTypesSection; 1262 DWARFSectionMap AppleNamespacesSection; 1263 DWARFSectionMap AppleObjCSection; 1264 DWARFSectionMap DebugNamesSection; 1265 1266 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) { 1267 return StringSwitch<DWARFSectionMap *>(Name) 1268 .Case("debug_info", &InfoSection) 1269 .Case("debug_loc", &LocSection) 1270 .Case("debug_loclists", &LocListsSection) 1271 .Case("debug_line", &LineSection) 1272 .Case("debug_str_offsets", &StringOffsetSection) 1273 .Case("debug_ranges", &RangeSection) 1274 .Case("debug_rnglists", &RnglistsSection) 1275 .Case("debug_info.dwo", &InfoDWOSection) 1276 .Case("debug_loc.dwo", &LocDWOSection) 1277 .Case("debug_line.dwo", &LineDWOSection) 1278 .Case("debug_names", &DebugNamesSection) 1279 .Case("debug_rnglists.dwo", &RnglistsDWOSection) 1280 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection) 1281 .Case("debug_addr", &AddrSection) 1282 .Case("apple_names", &AppleNamesSection) 1283 .Case("apple_types", &AppleTypesSection) 1284 .Case("apple_namespaces", &AppleNamespacesSection) 1285 .Case("apple_namespac", &AppleNamespacesSection) 1286 .Case("apple_objc", &AppleObjCSection) 1287 .Default(nullptr); 1288 } 1289 1290 StringRef AbbrevSection; 1291 StringRef ARangeSection; 1292 StringRef DebugFrameSection; 1293 StringRef EHFrameSection; 1294 StringRef StringSection; 1295 StringRef MacinfoSection; 1296 StringRef PubNamesSection; 1297 StringRef PubTypesSection; 1298 StringRef GnuPubNamesSection; 1299 StringRef AbbrevDWOSection; 1300 StringRef StringDWOSection; 1301 StringRef GnuPubTypesSection; 1302 StringRef CUIndexSection; 1303 StringRef GdbIndexSection; 1304 StringRef TUIndexSection; 1305 StringRef LineStringSection; 1306 1307 // A deque holding section data whose iterators are not invalidated when 1308 // new decompressed sections are inserted at the end. 1309 std::deque<SmallString<0>> UncompressedSections; 1310 1311 StringRef *mapSectionToMember(StringRef Name) { 1312 if (DWARFSection *Sec = mapNameToDWARFSection(Name)) 1313 return &Sec->Data; 1314 return StringSwitch<StringRef *>(Name) 1315 .Case("debug_abbrev", &AbbrevSection) 1316 .Case("debug_aranges", &ARangeSection) 1317 .Case("debug_frame", &DebugFrameSection) 1318 .Case("eh_frame", &EHFrameSection) 1319 .Case("debug_str", &StringSection) 1320 .Case("debug_macinfo", &MacinfoSection) 1321 .Case("debug_pubnames", &PubNamesSection) 1322 .Case("debug_pubtypes", &PubTypesSection) 1323 .Case("debug_gnu_pubnames", &GnuPubNamesSection) 1324 .Case("debug_gnu_pubtypes", &GnuPubTypesSection) 1325 .Case("debug_abbrev.dwo", &AbbrevDWOSection) 1326 .Case("debug_str.dwo", &StringDWOSection) 1327 .Case("debug_cu_index", &CUIndexSection) 1328 .Case("debug_tu_index", &TUIndexSection) 1329 .Case("gdb_index", &GdbIndexSection) 1330 .Case("debug_line_str", &LineStringSection) 1331 // Any more debug info sections go here. 1332 .Default(nullptr); 1333 } 1334 1335 /// If Sec is compressed section, decompresses and updates its contents 1336 /// provided by Data. Otherwise leaves it unchanged. 1337 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name, 1338 StringRef &Data) { 1339 if (!Decompressor::isCompressed(Sec)) 1340 return Error::success(); 1341 1342 Expected<Decompressor> Decompressor = 1343 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8); 1344 if (!Decompressor) 1345 return Decompressor.takeError(); 1346 1347 SmallString<0> Out; 1348 if (auto Err = Decompressor->resizeAndDecompress(Out)) 1349 return Err; 1350 1351 UncompressedSections.push_back(std::move(Out)); 1352 Data = UncompressedSections.back(); 1353 1354 return Error::success(); 1355 } 1356 1357 public: 1358 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections, 1359 uint8_t AddrSize, bool IsLittleEndian) 1360 : IsLittleEndian(IsLittleEndian) { 1361 for (const auto &SecIt : Sections) { 1362 if (StringRef *SectionData = mapSectionToMember(SecIt.first())) 1363 *SectionData = SecIt.second->getBuffer(); 1364 } 1365 } 1366 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L, 1367 function_ref<ErrorPolicy(Error)> HandleError) 1368 : IsLittleEndian(Obj.isLittleEndian()), 1369 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()), 1370 Obj(&Obj) { 1371 1372 StringMap<unsigned> SectionAmountMap; 1373 for (const SectionRef &Section : Obj.sections()) { 1374 StringRef Name; 1375 Section.getName(Name); 1376 ++SectionAmountMap[Name]; 1377 SectionNames.push_back({ Name, true }); 1378 1379 // Skip BSS and Virtual sections, they aren't interesting. 1380 if (Section.isBSS() || Section.isVirtual()) 1381 continue; 1382 1383 // Skip sections stripped by dsymutil. 1384 if (Section.isStripped()) 1385 continue; 1386 1387 StringRef Data; 1388 section_iterator RelocatedSection = Section.getRelocatedSection(); 1389 // Try to obtain an already relocated version of this section. 1390 // Else use the unrelocated section from the object file. We'll have to 1391 // apply relocations ourselves later. 1392 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data)) 1393 Section.getContents(Data); 1394 1395 if (auto Err = maybeDecompress(Section, Name, Data)) { 1396 ErrorPolicy EP = HandleError(createError( 1397 "failed to decompress '" + Name + "', ", std::move(Err))); 1398 if (EP == ErrorPolicy::Halt) 1399 return; 1400 continue; 1401 } 1402 1403 // Compressed sections names in GNU style starts from ".z", 1404 // at this point section is decompressed and we drop compression prefix. 1405 Name = Name.substr( 1406 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes. 1407 1408 // Map platform specific debug section names to DWARF standard section 1409 // names. 1410 Name = Obj.mapDebugSectionName(Name); 1411 1412 if (StringRef *SectionData = mapSectionToMember(Name)) { 1413 *SectionData = Data; 1414 if (Name == "debug_ranges") { 1415 // FIXME: Use the other dwo range section when we emit it. 1416 RangeDWOSection.Data = Data; 1417 } 1418 } else if (Name == "debug_types") { 1419 // Find debug_types data by section rather than name as there are 1420 // multiple, comdat grouped, debug_types sections. 1421 TypesSections[Section].Data = Data; 1422 } else if (Name == "debug_types.dwo") { 1423 TypesDWOSections[Section].Data = Data; 1424 } 1425 1426 if (RelocatedSection == Obj.section_end()) 1427 continue; 1428 1429 StringRef RelSecName; 1430 StringRef RelSecData; 1431 RelocatedSection->getName(RelSecName); 1432 1433 // If the section we're relocating was relocated already by the JIT, 1434 // then we used the relocated version above, so we do not need to process 1435 // relocations for it now. 1436 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData)) 1437 continue; 1438 1439 // In Mach-o files, the relocations do not need to be applied if 1440 // there is no load offset to apply. The value read at the 1441 // relocation point already factors in the section address 1442 // (actually applying the relocations will produce wrong results 1443 // as the section address will be added twice). 1444 if (!L && isa<MachOObjectFile>(&Obj)) 1445 continue; 1446 1447 RelSecName = RelSecName.substr( 1448 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes. 1449 1450 // TODO: Add support for relocations in other sections as needed. 1451 // Record relocations for the debug_info and debug_line sections. 1452 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName); 1453 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr; 1454 if (!Map) { 1455 // Find debug_types relocs by section rather than name as there are 1456 // multiple, comdat grouped, debug_types sections. 1457 if (RelSecName == "debug_types") 1458 Map = 1459 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection]) 1460 .Relocs; 1461 else if (RelSecName == "debug_types.dwo") 1462 Map = &static_cast<DWARFSectionMap &>( 1463 TypesDWOSections[*RelocatedSection]) 1464 .Relocs; 1465 else 1466 continue; 1467 } 1468 1469 if (Section.relocation_begin() == Section.relocation_end()) 1470 continue; 1471 1472 // Symbol to [address, section index] cache mapping. 1473 std::map<SymbolRef, SymInfo> AddrCache; 1474 for (const RelocationRef &Reloc : Section.relocations()) { 1475 // FIXME: it's not clear how to correctly handle scattered 1476 // relocations. 1477 if (isRelocScattered(Obj, Reloc)) 1478 continue; 1479 1480 Expected<SymInfo> SymInfoOrErr = 1481 getSymbolInfo(Obj, Reloc, L, AddrCache); 1482 if (!SymInfoOrErr) { 1483 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt) 1484 return; 1485 continue; 1486 } 1487 1488 object::RelocVisitor V(Obj); 1489 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address); 1490 if (V.error()) { 1491 SmallString<32> Type; 1492 Reloc.getTypeName(Type); 1493 ErrorPolicy EP = HandleError( 1494 createError("failed to compute relocation: " + Type + ", ", 1495 errorCodeToError(object_error::parse_failed))); 1496 if (EP == ErrorPolicy::Halt) 1497 return; 1498 continue; 1499 } 1500 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val}; 1501 Map->insert({Reloc.getOffset(), Rel}); 1502 } 1503 } 1504 1505 for (SectionName &S : SectionNames) 1506 if (SectionAmountMap[S.Name] > 1) 1507 S.IsNameUnique = false; 1508 } 1509 1510 Optional<RelocAddrEntry> find(const DWARFSection &S, 1511 uint64_t Pos) const override { 1512 auto &Sec = static_cast<const DWARFSectionMap &>(S); 1513 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos); 1514 if (AI == Sec.Relocs.end()) 1515 return None; 1516 return AI->second; 1517 } 1518 1519 const object::ObjectFile *getFile() const override { return Obj; } 1520 1521 ArrayRef<SectionName> getSectionNames() const override { 1522 return SectionNames; 1523 } 1524 1525 bool isLittleEndian() const override { return IsLittleEndian; } 1526 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; } 1527 const DWARFSection &getLineDWOSection() const override { 1528 return LineDWOSection; 1529 } 1530 const DWARFSection &getLocDWOSection() const override { 1531 return LocDWOSection; 1532 } 1533 StringRef getStringDWOSection() const override { return StringDWOSection; } 1534 const DWARFSection &getStringOffsetDWOSection() const override { 1535 return StringOffsetDWOSection; 1536 } 1537 const DWARFSection &getRangeDWOSection() const override { 1538 return RangeDWOSection; 1539 } 1540 const DWARFSection &getRnglistsDWOSection() const override { 1541 return RnglistsDWOSection; 1542 } 1543 const DWARFSection &getAddrSection() const override { return AddrSection; } 1544 StringRef getCUIndexSection() const override { return CUIndexSection; } 1545 StringRef getGdbIndexSection() const override { return GdbIndexSection; } 1546 StringRef getTUIndexSection() const override { return TUIndexSection; } 1547 1548 // DWARF v5 1549 const DWARFSection &getStringOffsetSection() const override { 1550 return StringOffsetSection; 1551 } 1552 StringRef getLineStringSection() const override { return LineStringSection; } 1553 1554 // Sections for DWARF5 split dwarf proposal. 1555 const DWARFSection &getInfoDWOSection() const override { 1556 return InfoDWOSection; 1557 } 1558 void forEachTypesDWOSections( 1559 function_ref<void(const DWARFSection &)> F) const override { 1560 for (auto &P : TypesDWOSections) 1561 F(P.second); 1562 } 1563 1564 StringRef getAbbrevSection() const override { return AbbrevSection; } 1565 const DWARFSection &getLocSection() const override { return LocSection; } 1566 const DWARFSection &getLoclistsSection() const override { return LocListsSection; } 1567 StringRef getARangeSection() const override { return ARangeSection; } 1568 StringRef getDebugFrameSection() const override { return DebugFrameSection; } 1569 StringRef getEHFrameSection() const override { return EHFrameSection; } 1570 const DWARFSection &getLineSection() const override { return LineSection; } 1571 StringRef getStringSection() const override { return StringSection; } 1572 const DWARFSection &getRangeSection() const override { return RangeSection; } 1573 const DWARFSection &getRnglistsSection() const override { 1574 return RnglistsSection; 1575 } 1576 StringRef getMacinfoSection() const override { return MacinfoSection; } 1577 StringRef getPubNamesSection() const override { return PubNamesSection; } 1578 StringRef getPubTypesSection() const override { return PubTypesSection; } 1579 StringRef getGnuPubNamesSection() const override { 1580 return GnuPubNamesSection; 1581 } 1582 StringRef getGnuPubTypesSection() const override { 1583 return GnuPubTypesSection; 1584 } 1585 const DWARFSection &getAppleNamesSection() const override { 1586 return AppleNamesSection; 1587 } 1588 const DWARFSection &getAppleTypesSection() const override { 1589 return AppleTypesSection; 1590 } 1591 const DWARFSection &getAppleNamespacesSection() const override { 1592 return AppleNamespacesSection; 1593 } 1594 const DWARFSection &getAppleObjCSection() const override { 1595 return AppleObjCSection; 1596 } 1597 const DWARFSection &getDebugNamesSection() const override { 1598 return DebugNamesSection; 1599 } 1600 1601 StringRef getFileName() const override { return FileName; } 1602 uint8_t getAddressSize() const override { return AddressSize; } 1603 const DWARFSection &getInfoSection() const override { return InfoSection; } 1604 void forEachTypesSections( 1605 function_ref<void(const DWARFSection &)> F) const override { 1606 for (auto &P : TypesSections) 1607 F(P.second); 1608 } 1609 }; 1610 } // namespace 1611 1612 std::unique_ptr<DWARFContext> 1613 DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L, 1614 function_ref<ErrorPolicy(Error)> HandleError, 1615 std::string DWPName) { 1616 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError); 1617 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName)); 1618 } 1619 1620 std::unique_ptr<DWARFContext> 1621 DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections, 1622 uint8_t AddrSize, bool isLittleEndian) { 1623 auto DObj = 1624 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian); 1625 return llvm::make_unique<DWARFContext>(std::move(DObj), ""); 1626 } 1627 1628 Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) { 1629 // Detect the architecture from the object file. We usually don't need OS 1630 // info to lookup a target and create register info. 1631 Triple TT; 1632 TT.setArch(Triple::ArchType(Obj.getArch())); 1633 TT.setVendor(Triple::UnknownVendor); 1634 TT.setOS(Triple::UnknownOS); 1635 std::string TargetLookupError; 1636 const Target *TheTarget = 1637 TargetRegistry::lookupTarget(TT.str(), TargetLookupError); 1638 if (!TargetLookupError.empty()) 1639 return createStringError(errc::invalid_argument, 1640 TargetLookupError.c_str()); 1641 RegInfo.reset(TheTarget->createMCRegInfo(TT.str())); 1642 return Error::success(); 1643 } 1644 1645 uint8_t DWARFContext::getCUAddrSize() { 1646 // In theory, different compile units may have different address byte 1647 // sizes, but for simplicity we just use the address byte size of the 1648 // last compile unit. In practice the address size field is repeated across 1649 // various DWARF headers (at least in version 5) to make it easier to dump 1650 // them independently, not to enable varying the address size. 1651 uint8_t Addr = 0; 1652 for (const auto &CU : compile_units()) { 1653 Addr = CU->getAddressByteSize(); 1654 break; 1655 } 1656 return Addr; 1657 } 1658 1659 void DWARFContext::dumpWarning(Error Warning) { 1660 handleAllErrors(std::move(Warning), [](ErrorInfoBase &Info) { 1661 WithColor::warning() << Info.message() << '\n'; 1662 }); 1663 } 1664