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