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