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