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