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