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