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