1 //===- DWARFContext.cpp ---------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 11 #include "llvm/ADT/STLExtras.h" 12 #include "llvm/ADT/SmallString.h" 13 #include "llvm/ADT/SmallVector.h" 14 #include "llvm/ADT/StringRef.h" 15 #include "llvm/ADT/StringSwitch.h" 16 #include "llvm/BinaryFormat/Dwarf.h" 17 #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h" 18 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h" 19 #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.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/RelocVisitor.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/MemoryBuffer.h" 45 #include "llvm/Support/Path.h" 46 #include "llvm/Support/TargetRegistry.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include <algorithm> 49 #include <cstdint> 50 #include <map> 51 #include <string> 52 #include <utility> 53 #include <vector> 54 55 using namespace llvm; 56 using namespace dwarf; 57 using namespace object; 58 59 #define DEBUG_TYPE "dwarf" 60 61 using DWARFLineTable = DWARFDebugLine::LineTable; 62 using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind; 63 using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind; 64 65 DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj, 66 std::string DWPName) 67 : DIContext(CK_DWARF), DWPName(std::move(DWPName)), DObj(std::move(DObj)) {} 68 69 DWARFContext::~DWARFContext() = default; 70 71 /// Dump the UUID load command. 72 static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) { 73 auto *MachO = dyn_cast<MachOObjectFile>(&Obj); 74 if (!MachO) 75 return; 76 for (auto LC : MachO->load_commands()) { 77 raw_ostream::uuid_t UUID; 78 if (LC.C.cmd == MachO::LC_UUID) { 79 if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) { 80 OS << "error: UUID load command is too short.\n"; 81 return; 82 } 83 OS << "UUID: "; 84 memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID)); 85 OS.write_uuid(UUID); 86 Triple T = MachO->getArchTriple(); 87 OS << " (" << T.getArchName() << ')'; 88 OS << ' ' << MachO->getFileName() << '\n'; 89 } 90 } 91 } 92 93 using ContributionCollection = 94 std::vector<Optional<StrOffsetsContributionDescriptor>>; 95 96 // Collect all the contributions to the string offsets table from all units, 97 // sort them by their starting offsets and remove duplicates. 98 static ContributionCollection 99 collectContributionData(DWARFContext::cu_iterator_range CUs, 100 DWARFContext::tu_section_iterator_range TUSs) { 101 ContributionCollection Contributions; 102 for (const auto &CU : CUs) 103 Contributions.push_back(CU->getStringOffsetsTableContribution()); 104 for (const auto &TUS : TUSs) 105 for (const auto &TU : TUS) 106 Contributions.push_back(TU->getStringOffsetsTableContribution()); 107 108 // Sort the contributions so that any invalid ones are placed at 109 // the start of the contributions vector. This way they are reported 110 // first. 111 std::sort(Contributions.begin(), Contributions.end(), 112 [](const Optional<StrOffsetsContributionDescriptor> &L, 113 const Optional<StrOffsetsContributionDescriptor> &R) { 114 if (L && R) 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::cu_iterator_range CUs, 137 DWARFContext::tu_section_iterator_range TUSs, bool LittleEndian) { 138 auto Contributions = collectContributionData(CUs, TUSs); 139 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0); 140 DataExtractor StrData(StringSection, LittleEndian, 0); 141 uint64_t SectionSize = StringOffsetsSection.Data.size(); 142 uint32_t Offset = 0; 143 for (auto &Contribution : Contributions) { 144 // Report an ill-formed contribution. 145 if (!Contribution) { 146 OS << "error: invalid contribution to string offsets table in section ." 147 << SectionName << ".\n"; 148 return; 149 } 150 151 dwarf::DwarfFormat Format = Contribution->getFormat(); 152 uint16_t Version = Contribution->getVersion(); 153 uint64_t ContributionHeader = Contribution->Base; 154 // In DWARF v5 there is a contribution header that immediately precedes 155 // the string offsets base (the location we have previously retrieved from 156 // the CU DIE's DW_AT_str_offsets attribute). The header is located either 157 // 8 or 16 bytes before the base, depending on the contribution's format. 158 if (Version >= 5) 159 ContributionHeader -= Format == DWARF32 ? 8 : 16; 160 161 // Detect overlapping contributions. 162 if (Offset > ContributionHeader) { 163 OS << "error: overlapping contributions to string offsets table in " 164 "section ." 165 << SectionName << ".\n"; 166 return; 167 } 168 // Report a gap in the table. 169 if (Offset < ContributionHeader) { 170 OS << format("0x%8.8x: Gap, length = ", Offset); 171 OS << (ContributionHeader - Offset) << "\n"; 172 } 173 OS << format("0x%8.8x: ", (uint32_t)ContributionHeader); 174 OS << "Contribution size = " << Contribution->Size 175 << ", Format = " << (Format == DWARF32 ? "DWARF32" : "DWARF64") 176 << ", Version = " << Version << "\n"; 177 178 Offset = Contribution->Base; 179 unsigned EntrySize = Contribution->getDwarfOffsetByteSize(); 180 while (Offset - Contribution->Base < Contribution->Size) { 181 OS << format("0x%8.8x: ", Offset); 182 // FIXME: We can only extract strings if the offset fits in 32 bits. 183 uint64_t StringOffset = 184 StrOffsetExt.getRelocatedValue(EntrySize, &Offset); 185 // Extract the string if we can and display it. Otherwise just report 186 // the offset. 187 if (StringOffset <= std::numeric_limits<uint32_t>::max()) { 188 uint32_t StringOffset32 = (uint32_t)StringOffset; 189 OS << format("%8.8x ", StringOffset32); 190 const char *S = StrData.getCStr(&StringOffset32); 191 if (S) 192 OS << format("\"%s\"", S); 193 } else 194 OS << format("%16.16" PRIx64 " ", StringOffset); 195 OS << "\n"; 196 } 197 } 198 // Report a gap at the end of the table. 199 if (Offset < SectionSize) { 200 OS << format("0x%8.8x: 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( 212 raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj, 213 const DWARFSection &StringOffsetsSection, StringRef StringSection, 214 DWARFContext::cu_iterator_range CUs, 215 DWARFContext::tu_section_iterator_range TUSs, bool LittleEndian, 216 unsigned MaxVersion) { 217 // If we have at least one (compile or type) unit with DWARF v5 or greater, 218 // we assume that the section is formatted like a DWARF v5 string offsets 219 // section. 220 if (MaxVersion >= 5) 221 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection, 222 StringSection, CUs, TUSs, LittleEndian); 223 else { 224 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0); 225 uint32_t offset = 0; 226 uint64_t size = StringOffsetsSection.Data.size(); 227 // Ensure that size is a multiple of the size of an entry. 228 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) { 229 OS << "error: size of ." << SectionName << " is not a multiple of " 230 << sizeof(uint32_t) << ".\n"; 231 size &= -(uint64_t)sizeof(uint32_t); 232 } 233 DataExtractor StrData(StringSection, LittleEndian, 0); 234 while (offset < size) { 235 OS << format("0x%8.8x: ", offset); 236 uint32_t StringOffset = strOffsetExt.getU32(&offset); 237 OS << format("%8.8x ", StringOffset); 238 const char *S = StrData.getCStr(&StringOffset); 239 if (S) 240 OS << format("\"%s\"", S); 241 OS << "\n"; 242 } 243 } 244 } 245 246 // We want to supply the Unit associated with a .debug_line[.dwo] table when 247 // we dump it, if possible, but still dump the table even if there isn't a Unit. 248 // Therefore, collect up handles on all the Units that point into the 249 // line-table section. 250 typedef std::map<uint64_t, DWARFUnit *> LineToUnitMap; 251 252 static LineToUnitMap 253 buildLineToUnitMap(DWARFContext::cu_iterator_range CUs, 254 DWARFContext::tu_section_iterator_range TUSections) { 255 LineToUnitMap LineToUnit; 256 for (const auto &CU : CUs) 257 if (auto CUDIE = CU->getUnitDIE()) 258 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) 259 LineToUnit.insert(std::make_pair(*StmtOffset, &*CU)); 260 for (const auto &TUS : TUSections) 261 for (const auto &TU : TUS) 262 if (auto TUDIE = TU->getUnitDIE()) 263 if (auto StmtOffset = toSectionOffset(TUDIE.find(DW_AT_stmt_list))) 264 LineToUnit.insert(std::make_pair(*StmtOffset, &*TU)); 265 return LineToUnit; 266 } 267 268 void DWARFContext::dump( 269 raw_ostream &OS, DIDumpOptions DumpOpts, 270 std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) { 271 272 Optional<uint64_t> DumpOffset; 273 uint64_t DumpType = DumpOpts.DumpType; 274 275 StringRef Extension = sys::path::extension(DObj->getFileName()); 276 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp"); 277 278 // Print UUID header. 279 const auto *ObjFile = DObj->getFile(); 280 if (DumpType & DIDT_UUID) 281 dumpUUID(OS, *ObjFile); 282 283 // Print a header for each explicitly-requested section. 284 // Otherwise just print one for non-empty sections. 285 // Only print empty .dwo section headers when dumping a .dwo file. 286 bool Explicit = DumpType != DIDT_All && !IsDWO; 287 bool ExplicitDWO = Explicit && IsDWO; 288 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID, 289 StringRef Section) { 290 DumpOffset = DumpOffsets[ID]; 291 unsigned Mask = 1U << ID; 292 bool Should = (DumpType & Mask) && (Explicit || !Section.empty()); 293 if (Should) 294 OS << "\n" << Name << " contents:\n"; 295 return Should; 296 }; 297 298 // Dump individual sections. 299 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev, 300 DObj->getAbbrevSection())) 301 getDebugAbbrev()->dump(OS); 302 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev, 303 DObj->getAbbrevDWOSection())) 304 getDebugAbbrevDWO()->dump(OS); 305 306 auto dumpDebugInfo = [&](bool IsExplicit, const char *Name, 307 DWARFSection Section, cu_iterator_range CUs) { 308 if (shouldDump(IsExplicit, Name, DIDT_ID_DebugInfo, Section.Data)) { 309 if (DumpOffset) 310 getDIEForOffset(DumpOffset.getValue()) 311 .dump(OS, 0, DumpOpts.noImplicitRecursion()); 312 else 313 for (const auto &CU : CUs) 314 CU->dump(OS, DumpOpts); 315 } 316 }; 317 dumpDebugInfo(Explicit, ".debug_info", DObj->getInfoSection(), 318 compile_units()); 319 dumpDebugInfo(ExplicitDWO, ".debug_info.dwo", DObj->getInfoDWOSection(), 320 dwo_compile_units()); 321 322 auto dumpDebugType = [&](const char *Name, 323 tu_section_iterator_range TUSections) { 324 OS << '\n' << Name << " contents:\n"; 325 DumpOffset = DumpOffsets[DIDT_ID_DebugTypes]; 326 for (const auto &TUS : TUSections) 327 for (const auto &TU : TUS) 328 if (DumpOffset) 329 TU->getDIEForOffset(*DumpOffset) 330 .dump(OS, 0, DumpOpts.noImplicitRecursion()); 331 else 332 TU->dump(OS, DumpOpts); 333 }; 334 if ((DumpType & DIDT_DebugTypes)) { 335 if (Explicit || getNumTypeUnits()) 336 dumpDebugType(".debug_types", type_unit_sections()); 337 if (ExplicitDWO || getNumDWOTypeUnits()) 338 dumpDebugType(".debug_types.dwo", dwo_type_unit_sections()); 339 } 340 341 if (shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc, 342 DObj->getLocSection().Data)) { 343 getDebugLoc()->dump(OS, getRegisterInfo(), DumpOffset); 344 } 345 if (shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc, 346 DObj->getLocDWOSection().Data)) { 347 getDebugLocDWO()->dump(OS, getRegisterInfo(), DumpOffset); 348 } 349 350 if (shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame, 351 DObj->getDebugFrameSection())) 352 getDebugFrame()->dump(OS, DumpOffset); 353 354 if (shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame, 355 DObj->getEHFrameSection())) 356 getEHFrame()->dump(OS, DumpOffset); 357 358 if (DumpType & DIDT_DebugMacro) { 359 if (Explicit || !getDebugMacro()->empty()) { 360 OS << "\n.debug_macinfo contents:\n"; 361 getDebugMacro()->dump(OS); 362 } 363 } 364 365 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges, 366 DObj->getARangeSection())) { 367 uint32_t offset = 0; 368 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0); 369 DWARFDebugArangeSet set; 370 while (set.extract(arangesData, &offset)) 371 set.dump(OS); 372 } 373 374 if (shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine, 375 DObj->getLineSection().Data)) { 376 LineToUnitMap LineToUnit = 377 buildLineToUnitMap(compile_units(), type_unit_sections()); 378 unsigned Offset = 0; 379 DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(), 380 0); 381 while (Offset < LineData.getData().size()) { 382 DWARFUnit *U = nullptr; 383 auto It = LineToUnit.find(Offset); 384 if (It != LineToUnit.end()) 385 U = It->second; 386 LineData.setAddressSize(U ? U->getAddressByteSize() : 0); 387 DWARFDebugLine::LineTable LineTable; 388 if (DumpOffset && Offset != *DumpOffset) { 389 // Find the size of this part of the line table section and skip it. 390 unsigned OldOffset = Offset; 391 LineTable.Prologue.parse(LineData, &Offset, *this, U); 392 Offset = OldOffset + LineTable.Prologue.TotalLength + 393 LineTable.Prologue.sizeofTotalLength(); 394 continue; 395 } 396 // Verbose dumping is done during parsing and not on the intermediate 397 // representation. 398 OS << "debug_line[" << format("0x%8.8x", Offset) << "]\n"; 399 unsigned OldOffset = Offset; 400 if (DumpOpts.Verbose) { 401 LineTable.parse(LineData, &Offset, *this, U, &OS); 402 } else { 403 LineTable.parse(LineData, &Offset, *this, U); 404 LineTable.dump(OS, DIDumpOptions()); 405 } 406 // Check for unparseable prologue, to avoid infinite loops. 407 if (OldOffset == Offset) 408 break; 409 } 410 } 411 412 if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine, 413 DObj->getLineDWOSection().Data)) { 414 LineToUnitMap LineToUnit = 415 buildLineToUnitMap(dwo_compile_units(), dwo_type_unit_sections()); 416 unsigned Offset = 0; 417 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(), 418 isLittleEndian(), 0); 419 while (Offset < LineData.getData().size()) { 420 DWARFUnit *U = nullptr; 421 auto It = LineToUnit.find(Offset); 422 if (It != LineToUnit.end()) 423 U = It->second; 424 DWARFDebugLine::LineTable LineTable; 425 unsigned OldOffset = Offset; 426 if (!LineTable.Prologue.parse(LineData, &Offset, *this, U)) 427 break; 428 if (!DumpOffset || OldOffset == *DumpOffset) 429 LineTable.dump(OS, DumpOpts); 430 } 431 } 432 433 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex, 434 DObj->getCUIndexSection())) { 435 getCUIndex().dump(OS); 436 } 437 438 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex, 439 DObj->getTUIndexSection())) { 440 getTUIndex().dump(OS); 441 } 442 443 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr, 444 DObj->getStringSection())) { 445 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0); 446 uint32_t offset = 0; 447 uint32_t strOffset = 0; 448 while (const char *s = strData.getCStr(&offset)) { 449 OS << format("0x%8.8x: \"%s\"\n", strOffset, s); 450 strOffset = offset; 451 } 452 } 453 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr, 454 DObj->getStringDWOSection())) { 455 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0); 456 uint32_t offset = 0; 457 uint32_t strDWOOffset = 0; 458 while (const char *s = strDWOData.getCStr(&offset)) { 459 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s); 460 strDWOOffset = offset; 461 } 462 } 463 if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr, 464 DObj->getLineStringSection())) { 465 DataExtractor strData(DObj->getLineStringSection(), isLittleEndian(), 0); 466 uint32_t offset = 0; 467 uint32_t strOffset = 0; 468 while (const char *s = strData.getCStr(&offset)) { 469 OS << format("0x%8.8x: \"%s\"\n", strOffset, s); 470 strOffset = offset; 471 } 472 } 473 474 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges, 475 DObj->getRangeSection().Data)) { 476 // In fact, different compile units may have different address byte 477 // sizes, but for simplicity we just use the address byte size of the 478 // last compile unit (there is no easy and fast way to associate address 479 // range list and the compile unit it describes). 480 // FIXME: savedAddressByteSize seems sketchy. 481 uint8_t savedAddressByteSize = 0; 482 for (const auto &CU : compile_units()) { 483 savedAddressByteSize = CU->getAddressByteSize(); 484 break; 485 } 486 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(), 487 isLittleEndian(), savedAddressByteSize); 488 uint32_t offset = 0; 489 DWARFDebugRangeList rangeList; 490 while (rangeList.extract(rangesData, &offset)) 491 rangeList.dump(OS); 492 } 493 494 if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists, 495 DObj->getRnglistsSection().Data)) { 496 DWARFDataExtractor rnglistData(*DObj, DObj->getRnglistsSection(), 497 isLittleEndian(), 0); 498 uint32_t Offset = 0; 499 while (rnglistData.isValidOffset(Offset)) { 500 DWARFDebugRnglists Rnglists; 501 uint32_t TableOffset = Offset; 502 if (Error Err = Rnglists.extract(rnglistData, &Offset)) { 503 errs() << "error: " + toString(std::move(Err)) << '\n'; 504 uint64_t Length = Rnglists.length(); 505 // Keep going after an error, if we can, assuming that the length field 506 // could be read. If it couldn't, stop reading the section. 507 if (Length == 0) 508 break; 509 Offset = TableOffset + Length; 510 } else 511 Rnglists.dump(OS); 512 } 513 } 514 515 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames, 516 DObj->getPubNamesSection())) 517 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false) 518 .dump(OS); 519 520 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes, 521 DObj->getPubTypesSection())) 522 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false) 523 .dump(OS); 524 525 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames, 526 DObj->getGnuPubNamesSection())) 527 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(), 528 true /* GnuStyle */) 529 .dump(OS); 530 531 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes, 532 DObj->getGnuPubTypesSection())) 533 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(), 534 true /* GnuStyle */) 535 .dump(OS); 536 537 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets, 538 DObj->getStringOffsetSection().Data)) 539 dumpStringOffsetsSection( 540 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(), 541 DObj->getStringSection(), compile_units(), type_unit_sections(), 542 isLittleEndian(), getMaxVersion()); 543 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets, 544 DObj->getStringOffsetDWOSection().Data)) 545 dumpStringOffsetsSection( 546 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(), 547 DObj->getStringDWOSection(), dwo_compile_units(), 548 dwo_type_unit_sections(), isLittleEndian(), getMaxVersion()); 549 550 if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex, 551 DObj->getGdbIndexSection())) { 552 getGdbIndex().dump(OS); 553 } 554 555 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames, 556 DObj->getAppleNamesSection().Data)) 557 getAppleNames().dump(OS); 558 559 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes, 560 DObj->getAppleTypesSection().Data)) 561 getAppleTypes().dump(OS); 562 563 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces, 564 DObj->getAppleNamespacesSection().Data)) 565 getAppleNamespaces().dump(OS); 566 567 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC, 568 DObj->getAppleObjCSection().Data)) 569 getAppleObjC().dump(OS); 570 if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames, 571 DObj->getDebugNamesSection().Data)) 572 getDebugNames().dump(OS); 573 } 574 575 DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) { 576 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection(), true); 577 578 if (const auto &CUI = getCUIndex()) { 579 if (const auto *R = CUI.getFromHash(Hash)) 580 return DWOCUs.getUnitForIndexEntry(*R); 581 return nullptr; 582 } 583 584 // If there's no index, just search through the CUs in the DWO - there's 585 // probably only one unless this is something like LTO - though an in-process 586 // built/cached lookup table could be used in that case to improve repeated 587 // lookups of different CUs in the DWO. 588 for (const auto &DWOCU : dwo_compile_units()) 589 if (DWOCU->getDWOId() == Hash) 590 return DWOCU.get(); 591 return nullptr; 592 } 593 594 DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) { 595 parseCompileUnits(); 596 if (auto *CU = CUs.getUnitForOffset(Offset)) 597 return CU->getDIEForOffset(Offset); 598 return DWARFDie(); 599 } 600 601 bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) { 602 bool Success = true; 603 DWARFVerifier verifier(OS, *this, DumpOpts); 604 605 Success &= verifier.handleDebugAbbrev(); 606 if (DumpOpts.DumpType & DIDT_DebugInfo) 607 Success &= verifier.handleDebugInfo(); 608 if (DumpOpts.DumpType & DIDT_DebugLine) 609 Success &= verifier.handleDebugLine(); 610 Success &= verifier.handleAccelTables(); 611 return Success; 612 } 613 614 const DWARFUnitIndex &DWARFContext::getCUIndex() { 615 if (CUIndex) 616 return *CUIndex; 617 618 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0); 619 620 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO); 621 CUIndex->parse(CUIndexData); 622 return *CUIndex; 623 } 624 625 const DWARFUnitIndex &DWARFContext::getTUIndex() { 626 if (TUIndex) 627 return *TUIndex; 628 629 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0); 630 631 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES); 632 TUIndex->parse(TUIndexData); 633 return *TUIndex; 634 } 635 636 DWARFGdbIndex &DWARFContext::getGdbIndex() { 637 if (GdbIndex) 638 return *GdbIndex; 639 640 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0); 641 GdbIndex = llvm::make_unique<DWARFGdbIndex>(); 642 GdbIndex->parse(GdbIndexData); 643 return *GdbIndex; 644 } 645 646 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() { 647 if (Abbrev) 648 return Abbrev.get(); 649 650 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0); 651 652 Abbrev.reset(new DWARFDebugAbbrev()); 653 Abbrev->extract(abbrData); 654 return Abbrev.get(); 655 } 656 657 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() { 658 if (AbbrevDWO) 659 return AbbrevDWO.get(); 660 661 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0); 662 AbbrevDWO.reset(new DWARFDebugAbbrev()); 663 AbbrevDWO->extract(abbrData); 664 return AbbrevDWO.get(); 665 } 666 667 const DWARFDebugLoc *DWARFContext::getDebugLoc() { 668 if (Loc) 669 return Loc.get(); 670 671 Loc.reset(new DWARFDebugLoc); 672 // assume all compile units have the same address byte size 673 if (getNumCompileUnits()) { 674 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(), 675 getCompileUnitAtIndex(0)->getAddressByteSize()); 676 Loc->parse(LocData); 677 } 678 return Loc.get(); 679 } 680 681 const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() { 682 if (LocDWO) 683 return LocDWO.get(); 684 685 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0); 686 LocDWO.reset(new DWARFDebugLocDWO()); 687 LocDWO->parse(LocData); 688 return LocDWO.get(); 689 } 690 691 const DWARFDebugAranges *DWARFContext::getDebugAranges() { 692 if (Aranges) 693 return Aranges.get(); 694 695 Aranges.reset(new DWARFDebugAranges()); 696 Aranges->generate(this); 697 return Aranges.get(); 698 } 699 700 const DWARFDebugFrame *DWARFContext::getDebugFrame() { 701 if (DebugFrame) 702 return DebugFrame.get(); 703 704 // There's a "bug" in the DWARFv3 standard with respect to the target address 705 // size within debug frame sections. While DWARF is supposed to be independent 706 // of its container, FDEs have fields with size being "target address size", 707 // which isn't specified in DWARF in general. It's only specified for CUs, but 708 // .eh_frame can appear without a .debug_info section. Follow the example of 709 // other tools (libdwarf) and extract this from the container (ObjectFile 710 // provides this information). This problem is fixed in DWARFv4 711 // See this dwarf-discuss discussion for more details: 712 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html 713 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(), 714 DObj->getAddressSize()); 715 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */)); 716 DebugFrame->parse(debugFrameData); 717 return DebugFrame.get(); 718 } 719 720 const DWARFDebugFrame *DWARFContext::getEHFrame() { 721 if (EHFrame) 722 return EHFrame.get(); 723 724 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(), 725 DObj->getAddressSize()); 726 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */)); 727 DebugFrame->parse(debugFrameData); 728 return DebugFrame.get(); 729 } 730 731 const DWARFDebugMacro *DWARFContext::getDebugMacro() { 732 if (Macro) 733 return Macro.get(); 734 735 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0); 736 Macro.reset(new DWARFDebugMacro()); 737 Macro->parse(MacinfoData); 738 return Macro.get(); 739 } 740 741 template <typename T> 742 static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj, 743 const DWARFSection &Section, StringRef StringSection, 744 bool IsLittleEndian) { 745 if (Cache) 746 return *Cache; 747 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0); 748 DataExtractor StrData(StringSection, IsLittleEndian, 0); 749 Cache.reset(new T(AccelSection, StrData)); 750 if (Error E = Cache->extract()) 751 llvm::consumeError(std::move(E)); 752 return *Cache; 753 } 754 755 const DWARFDebugNames &DWARFContext::getDebugNames() { 756 return getAccelTable(Names, *DObj, DObj->getDebugNamesSection(), 757 DObj->getStringSection(), isLittleEndian()); 758 } 759 760 const AppleAcceleratorTable &DWARFContext::getAppleNames() { 761 return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(), 762 DObj->getStringSection(), isLittleEndian()); 763 } 764 765 const AppleAcceleratorTable &DWARFContext::getAppleTypes() { 766 return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(), 767 DObj->getStringSection(), isLittleEndian()); 768 } 769 770 const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() { 771 return getAccelTable(AppleNamespaces, *DObj, 772 DObj->getAppleNamespacesSection(), 773 DObj->getStringSection(), isLittleEndian()); 774 } 775 776 const AppleAcceleratorTable &DWARFContext::getAppleObjC() { 777 return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(), 778 DObj->getStringSection(), isLittleEndian()); 779 } 780 781 const DWARFLineTable * 782 DWARFContext::getLineTableForUnit(DWARFUnit *U) { 783 if (!Line) 784 Line.reset(new DWARFDebugLine); 785 786 auto UnitDIE = U->getUnitDIE(); 787 if (!UnitDIE) 788 return nullptr; 789 790 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list)); 791 if (!Offset) 792 return nullptr; // No line table for this compile unit. 793 794 uint32_t stmtOffset = *Offset + U->getLineTableOffset(); 795 // See if the line table is cached. 796 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset)) 797 return lt; 798 799 // Make sure the offset is good before we try to parse. 800 if (stmtOffset >= U->getLineSection().Data.size()) 801 return nullptr; 802 803 // We have to parse it first. 804 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(), 805 U->getAddressByteSize()); 806 return Line->getOrParseLineTable(lineData, stmtOffset, *this, U); 807 } 808 809 void DWARFContext::parseCompileUnits() { 810 CUs.parse(*this, DObj->getInfoSection()); 811 } 812 813 void DWARFContext::parseTypeUnits() { 814 if (!TUs.empty()) 815 return; 816 DObj->forEachTypesSections([&](const DWARFSection &S) { 817 TUs.emplace_back(); 818 TUs.back().parse(*this, S); 819 }); 820 } 821 822 void DWARFContext::parseDWOCompileUnits() { 823 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection()); 824 } 825 826 void DWARFContext::parseDWOTypeUnits() { 827 if (!DWOTUs.empty()) 828 return; 829 DObj->forEachTypesDWOSections([&](const DWARFSection &S) { 830 DWOTUs.emplace_back(); 831 DWOTUs.back().parseDWO(*this, S); 832 }); 833 } 834 835 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) { 836 parseCompileUnits(); 837 return CUs.getUnitForOffset(Offset); 838 } 839 840 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) { 841 // First, get the offset of the compile unit. 842 uint32_t CUOffset = getDebugAranges()->findAddress(Address); 843 // Retrieve the compile unit. 844 return getCompileUnitForOffset(CUOffset); 845 } 846 847 DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) { 848 DIEsForAddress Result; 849 850 DWARFCompileUnit *CU = getCompileUnitForAddress(Address); 851 if (!CU) 852 return Result; 853 854 Result.CompileUnit = CU; 855 Result.FunctionDIE = CU->getSubroutineForAddress(Address); 856 857 std::vector<DWARFDie> Worklist; 858 Worklist.push_back(Result.FunctionDIE); 859 while (!Worklist.empty()) { 860 DWARFDie DIE = Worklist.back(); 861 Worklist.pop_back(); 862 863 if (DIE.getTag() == DW_TAG_lexical_block && 864 DIE.addressRangeContainsAddress(Address)) { 865 Result.BlockDIE = DIE; 866 break; 867 } 868 869 for (auto Child : DIE) 870 Worklist.push_back(Child); 871 } 872 873 return Result; 874 } 875 876 static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU, 877 uint64_t Address, 878 FunctionNameKind Kind, 879 std::string &FunctionName, 880 uint32_t &StartLine) { 881 // The address may correspond to instruction in some inlined function, 882 // so we have to build the chain of inlined functions and take the 883 // name of the topmost function in it. 884 SmallVector<DWARFDie, 4> InlinedChain; 885 CU->getInlinedChainForAddress(Address, InlinedChain); 886 if (InlinedChain.empty()) 887 return false; 888 889 const DWARFDie &DIE = InlinedChain[0]; 890 bool FoundResult = false; 891 const char *Name = nullptr; 892 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) { 893 FunctionName = Name; 894 FoundResult = true; 895 } 896 if (auto DeclLineResult = DIE.getDeclLine()) { 897 StartLine = DeclLineResult; 898 FoundResult = true; 899 } 900 901 return FoundResult; 902 } 903 904 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address, 905 DILineInfoSpecifier Spec) { 906 DILineInfo Result; 907 908 DWARFCompileUnit *CU = getCompileUnitForAddress(Address); 909 if (!CU) 910 return Result; 911 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, 912 Result.FunctionName, 913 Result.StartLine); 914 if (Spec.FLIKind != FileLineInfoKind::None) { 915 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU)) 916 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(), 917 Spec.FLIKind, Result); 918 } 919 return Result; 920 } 921 922 DILineInfoTable 923 DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size, 924 DILineInfoSpecifier Spec) { 925 DILineInfoTable Lines; 926 DWARFCompileUnit *CU = getCompileUnitForAddress(Address); 927 if (!CU) 928 return Lines; 929 930 std::string FunctionName = "<invalid>"; 931 uint32_t StartLine = 0; 932 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName, 933 StartLine); 934 935 // If the Specifier says we don't need FileLineInfo, just 936 // return the top-most function at the starting address. 937 if (Spec.FLIKind == FileLineInfoKind::None) { 938 DILineInfo Result; 939 Result.FunctionName = FunctionName; 940 Result.StartLine = StartLine; 941 Lines.push_back(std::make_pair(Address, Result)); 942 return Lines; 943 } 944 945 const DWARFLineTable *LineTable = getLineTableForUnit(CU); 946 947 // Get the index of row we're looking for in the line table. 948 std::vector<uint32_t> RowVector; 949 if (!LineTable->lookupAddressRange(Address, Size, RowVector)) 950 return Lines; 951 952 for (uint32_t RowIndex : RowVector) { 953 // Take file number and line/column from the row. 954 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex]; 955 DILineInfo Result; 956 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(), 957 Spec.FLIKind, Result.FileName); 958 Result.FunctionName = FunctionName; 959 Result.Line = Row.Line; 960 Result.Column = Row.Column; 961 Result.StartLine = StartLine; 962 Lines.push_back(std::make_pair(Row.Address, Result)); 963 } 964 965 return Lines; 966 } 967 968 DIInliningInfo 969 DWARFContext::getInliningInfoForAddress(uint64_t Address, 970 DILineInfoSpecifier Spec) { 971 DIInliningInfo InliningInfo; 972 973 DWARFCompileUnit *CU = getCompileUnitForAddress(Address); 974 if (!CU) 975 return InliningInfo; 976 977 const DWARFLineTable *LineTable = nullptr; 978 SmallVector<DWARFDie, 4> InlinedChain; 979 CU->getInlinedChainForAddress(Address, InlinedChain); 980 if (InlinedChain.size() == 0) { 981 // If there is no DIE for address (e.g. it is in unavailable .dwo file), 982 // try to at least get file/line info from symbol table. 983 if (Spec.FLIKind != FileLineInfoKind::None) { 984 DILineInfo Frame; 985 LineTable = getLineTableForUnit(CU); 986 if (LineTable && 987 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(), 988 Spec.FLIKind, Frame)) 989 InliningInfo.addFrame(Frame); 990 } 991 return InliningInfo; 992 } 993 994 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0; 995 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) { 996 DWARFDie &FunctionDIE = InlinedChain[i]; 997 DILineInfo Frame; 998 // Get function name if necessary. 999 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind)) 1000 Frame.FunctionName = Name; 1001 if (auto DeclLineResult = FunctionDIE.getDeclLine()) 1002 Frame.StartLine = DeclLineResult; 1003 if (Spec.FLIKind != FileLineInfoKind::None) { 1004 if (i == 0) { 1005 // For the topmost frame, initialize the line table of this 1006 // compile unit and fetch file/line info from it. 1007 LineTable = getLineTableForUnit(CU); 1008 // For the topmost routine, get file/line info from line table. 1009 if (LineTable) 1010 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(), 1011 Spec.FLIKind, Frame); 1012 } else { 1013 // Otherwise, use call file, call line and call column from 1014 // previous DIE in inlined chain. 1015 if (LineTable) 1016 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(), 1017 Spec.FLIKind, Frame.FileName); 1018 Frame.Line = CallLine; 1019 Frame.Column = CallColumn; 1020 Frame.Discriminator = CallDiscriminator; 1021 } 1022 // Get call file/line/column of a current DIE. 1023 if (i + 1 < n) { 1024 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn, 1025 CallDiscriminator); 1026 } 1027 } 1028 InliningInfo.addFrame(Frame); 1029 } 1030 return InliningInfo; 1031 } 1032 1033 std::shared_ptr<DWARFContext> 1034 DWARFContext::getDWOContext(StringRef AbsolutePath) { 1035 if (auto S = DWP.lock()) { 1036 DWARFContext *Ctxt = S->Context.get(); 1037 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt); 1038 } 1039 1040 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath]; 1041 1042 if (auto S = Entry->lock()) { 1043 DWARFContext *Ctxt = S->Context.get(); 1044 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt); 1045 } 1046 1047 Expected<OwningBinary<ObjectFile>> Obj = [&] { 1048 if (!CheckedForDWP) { 1049 SmallString<128> DWPName; 1050 auto Obj = object::ObjectFile::createObjectFile( 1051 this->DWPName.empty() 1052 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName) 1053 : StringRef(this->DWPName)); 1054 if (Obj) { 1055 Entry = &DWP; 1056 return Obj; 1057 } else { 1058 CheckedForDWP = true; 1059 // TODO: Should this error be handled (maybe in a high verbosity mode) 1060 // before falling back to .dwo files? 1061 consumeError(Obj.takeError()); 1062 } 1063 } 1064 1065 return object::ObjectFile::createObjectFile(AbsolutePath); 1066 }(); 1067 1068 if (!Obj) { 1069 // TODO: Actually report errors helpfully. 1070 consumeError(Obj.takeError()); 1071 return nullptr; 1072 } 1073 1074 auto S = std::make_shared<DWOFile>(); 1075 S->File = std::move(Obj.get()); 1076 S->Context = DWARFContext::create(*S->File.getBinary()); 1077 *Entry = S; 1078 auto *Ctxt = S->Context.get(); 1079 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt); 1080 } 1081 1082 static Error createError(const Twine &Reason, llvm::Error E) { 1083 return make_error<StringError>(Reason + toString(std::move(E)), 1084 inconvertibleErrorCode()); 1085 } 1086 1087 /// SymInfo contains information about symbol: it's address 1088 /// and section index which is -1LL for absolute symbols. 1089 struct SymInfo { 1090 uint64_t Address; 1091 uint64_t SectionIndex; 1092 }; 1093 1094 /// Returns the address of symbol relocation used against and a section index. 1095 /// Used for futher relocations computation. Symbol's section load address is 1096 static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj, 1097 const RelocationRef &Reloc, 1098 const LoadedObjectInfo *L, 1099 std::map<SymbolRef, SymInfo> &Cache) { 1100 SymInfo Ret = {0, (uint64_t)-1LL}; 1101 object::section_iterator RSec = Obj.section_end(); 1102 object::symbol_iterator Sym = Reloc.getSymbol(); 1103 1104 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end(); 1105 // First calculate the address of the symbol or section as it appears 1106 // in the object file 1107 if (Sym != Obj.symbol_end()) { 1108 bool New; 1109 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}}); 1110 if (!New) 1111 return CacheIt->second; 1112 1113 Expected<uint64_t> SymAddrOrErr = Sym->getAddress(); 1114 if (!SymAddrOrErr) 1115 return createError("failed to compute symbol address: ", 1116 SymAddrOrErr.takeError()); 1117 1118 // Also remember what section this symbol is in for later 1119 auto SectOrErr = Sym->getSection(); 1120 if (!SectOrErr) 1121 return createError("failed to get symbol section: ", 1122 SectOrErr.takeError()); 1123 1124 RSec = *SectOrErr; 1125 Ret.Address = *SymAddrOrErr; 1126 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) { 1127 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl()); 1128 Ret.Address = RSec->getAddress(); 1129 } 1130 1131 if (RSec != Obj.section_end()) 1132 Ret.SectionIndex = RSec->getIndex(); 1133 1134 // If we are given load addresses for the sections, we need to adjust: 1135 // SymAddr = (Address of Symbol Or Section in File) - 1136 // (Address of Section in File) + 1137 // (Load Address of Section) 1138 // RSec is now either the section being targeted or the section 1139 // containing the symbol being targeted. In either case, 1140 // we need to perform the same computation. 1141 if (L && RSec != Obj.section_end()) 1142 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec)) 1143 Ret.Address += SectionLoadAddress - RSec->getAddress(); 1144 1145 if (CacheIt != Cache.end()) 1146 CacheIt->second = Ret; 1147 1148 return Ret; 1149 } 1150 1151 static bool isRelocScattered(const object::ObjectFile &Obj, 1152 const RelocationRef &Reloc) { 1153 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj); 1154 if (!MachObj) 1155 return false; 1156 // MachO also has relocations that point to sections and 1157 // scattered relocations. 1158 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl()); 1159 return MachObj->isRelocationScattered(RelocInfo); 1160 } 1161 1162 ErrorPolicy DWARFContext::defaultErrorHandler(Error E) { 1163 errs() << "error: " + toString(std::move(E)) << '\n'; 1164 return ErrorPolicy::Continue; 1165 } 1166 1167 namespace { 1168 struct DWARFSectionMap final : public DWARFSection { 1169 RelocAddrMap Relocs; 1170 }; 1171 1172 class DWARFObjInMemory final : public DWARFObject { 1173 bool IsLittleEndian; 1174 uint8_t AddressSize; 1175 StringRef FileName; 1176 const object::ObjectFile *Obj = nullptr; 1177 std::vector<SectionName> SectionNames; 1178 1179 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap, 1180 std::map<object::SectionRef, unsigned>>; 1181 1182 TypeSectionMap TypesSections; 1183 TypeSectionMap TypesDWOSections; 1184 1185 DWARFSectionMap InfoSection; 1186 DWARFSectionMap LocSection; 1187 DWARFSectionMap LineSection; 1188 DWARFSectionMap RangeSection; 1189 DWARFSectionMap RnglistsSection; 1190 DWARFSectionMap StringOffsetSection; 1191 DWARFSectionMap InfoDWOSection; 1192 DWARFSectionMap LineDWOSection; 1193 DWARFSectionMap LocDWOSection; 1194 DWARFSectionMap StringOffsetDWOSection; 1195 DWARFSectionMap RangeDWOSection; 1196 DWARFSectionMap AddrSection; 1197 DWARFSectionMap AppleNamesSection; 1198 DWARFSectionMap AppleTypesSection; 1199 DWARFSectionMap AppleNamespacesSection; 1200 DWARFSectionMap AppleObjCSection; 1201 DWARFSectionMap DebugNamesSection; 1202 1203 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) { 1204 return StringSwitch<DWARFSectionMap *>(Name) 1205 .Case("debug_info", &InfoSection) 1206 .Case("debug_loc", &LocSection) 1207 .Case("debug_line", &LineSection) 1208 .Case("debug_str_offsets", &StringOffsetSection) 1209 .Case("debug_ranges", &RangeSection) 1210 .Case("debug_rnglists", &RnglistsSection) 1211 .Case("debug_info.dwo", &InfoDWOSection) 1212 .Case("debug_loc.dwo", &LocDWOSection) 1213 .Case("debug_line.dwo", &LineDWOSection) 1214 .Case("debug_names", &DebugNamesSection) 1215 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection) 1216 .Case("debug_addr", &AddrSection) 1217 .Case("apple_names", &AppleNamesSection) 1218 .Case("apple_types", &AppleTypesSection) 1219 .Case("apple_namespaces", &AppleNamespacesSection) 1220 .Case("apple_namespac", &AppleNamespacesSection) 1221 .Case("apple_objc", &AppleObjCSection) 1222 .Default(nullptr); 1223 } 1224 1225 StringRef AbbrevSection; 1226 StringRef ARangeSection; 1227 StringRef DebugFrameSection; 1228 StringRef EHFrameSection; 1229 StringRef StringSection; 1230 StringRef MacinfoSection; 1231 StringRef PubNamesSection; 1232 StringRef PubTypesSection; 1233 StringRef GnuPubNamesSection; 1234 StringRef AbbrevDWOSection; 1235 StringRef StringDWOSection; 1236 StringRef GnuPubTypesSection; 1237 StringRef CUIndexSection; 1238 StringRef GdbIndexSection; 1239 StringRef TUIndexSection; 1240 StringRef LineStringSection; 1241 1242 SmallVector<SmallString<32>, 4> UncompressedSections; 1243 1244 StringRef *mapSectionToMember(StringRef Name) { 1245 if (DWARFSection *Sec = mapNameToDWARFSection(Name)) 1246 return &Sec->Data; 1247 return StringSwitch<StringRef *>(Name) 1248 .Case("debug_abbrev", &AbbrevSection) 1249 .Case("debug_aranges", &ARangeSection) 1250 .Case("debug_frame", &DebugFrameSection) 1251 .Case("eh_frame", &EHFrameSection) 1252 .Case("debug_str", &StringSection) 1253 .Case("debug_macinfo", &MacinfoSection) 1254 .Case("debug_pubnames", &PubNamesSection) 1255 .Case("debug_pubtypes", &PubTypesSection) 1256 .Case("debug_gnu_pubnames", &GnuPubNamesSection) 1257 .Case("debug_gnu_pubtypes", &GnuPubTypesSection) 1258 .Case("debug_abbrev.dwo", &AbbrevDWOSection) 1259 .Case("debug_str.dwo", &StringDWOSection) 1260 .Case("debug_cu_index", &CUIndexSection) 1261 .Case("debug_tu_index", &TUIndexSection) 1262 .Case("gdb_index", &GdbIndexSection) 1263 .Case("debug_line_str", &LineStringSection) 1264 // Any more debug info sections go here. 1265 .Default(nullptr); 1266 } 1267 1268 /// If Sec is compressed section, decompresses and updates its contents 1269 /// provided by Data. Otherwise leaves it unchanged. 1270 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name, 1271 StringRef &Data) { 1272 if (!Decompressor::isCompressed(Sec)) 1273 return Error::success(); 1274 1275 Expected<Decompressor> Decompressor = 1276 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8); 1277 if (!Decompressor) 1278 return Decompressor.takeError(); 1279 1280 SmallString<32> Out; 1281 if (auto Err = Decompressor->resizeAndDecompress(Out)) 1282 return Err; 1283 1284 UncompressedSections.emplace_back(std::move(Out)); 1285 Data = UncompressedSections.back(); 1286 1287 return Error::success(); 1288 } 1289 1290 public: 1291 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections, 1292 uint8_t AddrSize, bool IsLittleEndian) 1293 : IsLittleEndian(IsLittleEndian) { 1294 for (const auto &SecIt : Sections) { 1295 if (StringRef *SectionData = mapSectionToMember(SecIt.first())) 1296 *SectionData = SecIt.second->getBuffer(); 1297 } 1298 } 1299 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L, 1300 function_ref<ErrorPolicy(Error)> HandleError) 1301 : IsLittleEndian(Obj.isLittleEndian()), 1302 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()), 1303 Obj(&Obj) { 1304 1305 StringMap<unsigned> SectionAmountMap; 1306 for (const SectionRef &Section : Obj.sections()) { 1307 StringRef Name; 1308 Section.getName(Name); 1309 ++SectionAmountMap[Name]; 1310 SectionNames.push_back({ Name, true }); 1311 1312 // Skip BSS and Virtual sections, they aren't interesting. 1313 if (Section.isBSS() || Section.isVirtual()) 1314 continue; 1315 1316 // Skip sections stripped by dsymutil. 1317 if (Section.isStripped()) 1318 continue; 1319 1320 StringRef Data; 1321 section_iterator RelocatedSection = Section.getRelocatedSection(); 1322 // Try to obtain an already relocated version of this section. 1323 // Else use the unrelocated section from the object file. We'll have to 1324 // apply relocations ourselves later. 1325 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data)) 1326 Section.getContents(Data); 1327 1328 if (auto Err = maybeDecompress(Section, Name, Data)) { 1329 ErrorPolicy EP = HandleError(createError( 1330 "failed to decompress '" + Name + "', ", std::move(Err))); 1331 if (EP == ErrorPolicy::Halt) 1332 return; 1333 continue; 1334 } 1335 1336 // Compressed sections names in GNU style starts from ".z", 1337 // at this point section is decompressed and we drop compression prefix. 1338 Name = Name.substr( 1339 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes. 1340 1341 // Map platform specific debug section names to DWARF standard section 1342 // names. 1343 Name = Obj.mapDebugSectionName(Name); 1344 1345 if (StringRef *SectionData = mapSectionToMember(Name)) { 1346 *SectionData = Data; 1347 if (Name == "debug_ranges") { 1348 // FIXME: Use the other dwo range section when we emit it. 1349 RangeDWOSection.Data = Data; 1350 } 1351 } else if (Name == "debug_types") { 1352 // Find debug_types data by section rather than name as there are 1353 // multiple, comdat grouped, debug_types sections. 1354 TypesSections[Section].Data = Data; 1355 } else if (Name == "debug_types.dwo") { 1356 TypesDWOSections[Section].Data = Data; 1357 } 1358 1359 if (RelocatedSection == Obj.section_end()) 1360 continue; 1361 1362 StringRef RelSecName; 1363 StringRef RelSecData; 1364 RelocatedSection->getName(RelSecName); 1365 1366 // If the section we're relocating was relocated already by the JIT, 1367 // then we used the relocated version above, so we do not need to process 1368 // relocations for it now. 1369 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData)) 1370 continue; 1371 1372 // In Mach-o files, the relocations do not need to be applied if 1373 // there is no load offset to apply. The value read at the 1374 // relocation point already factors in the section address 1375 // (actually applying the relocations will produce wrong results 1376 // as the section address will be added twice). 1377 if (!L && isa<MachOObjectFile>(&Obj)) 1378 continue; 1379 1380 RelSecName = RelSecName.substr( 1381 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes. 1382 1383 // TODO: Add support for relocations in other sections as needed. 1384 // Record relocations for the debug_info and debug_line sections. 1385 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName); 1386 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr; 1387 if (!Map) { 1388 // Find debug_types relocs by section rather than name as there are 1389 // multiple, comdat grouped, debug_types sections. 1390 if (RelSecName == "debug_types") 1391 Map = 1392 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection]) 1393 .Relocs; 1394 else if (RelSecName == "debug_types.dwo") 1395 Map = &static_cast<DWARFSectionMap &>( 1396 TypesDWOSections[*RelocatedSection]) 1397 .Relocs; 1398 else 1399 continue; 1400 } 1401 1402 if (Section.relocation_begin() == Section.relocation_end()) 1403 continue; 1404 1405 // Symbol to [address, section index] cache mapping. 1406 std::map<SymbolRef, SymInfo> AddrCache; 1407 for (const RelocationRef &Reloc : Section.relocations()) { 1408 // FIXME: it's not clear how to correctly handle scattered 1409 // relocations. 1410 if (isRelocScattered(Obj, Reloc)) 1411 continue; 1412 1413 Expected<SymInfo> SymInfoOrErr = 1414 getSymbolInfo(Obj, Reloc, L, AddrCache); 1415 if (!SymInfoOrErr) { 1416 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt) 1417 return; 1418 continue; 1419 } 1420 1421 object::RelocVisitor V(Obj); 1422 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address); 1423 if (V.error()) { 1424 SmallString<32> Type; 1425 Reloc.getTypeName(Type); 1426 ErrorPolicy EP = HandleError( 1427 createError("failed to compute relocation: " + Type + ", ", 1428 errorCodeToError(object_error::parse_failed))); 1429 if (EP == ErrorPolicy::Halt) 1430 return; 1431 continue; 1432 } 1433 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val}; 1434 Map->insert({Reloc.getOffset(), Rel}); 1435 } 1436 } 1437 1438 for (SectionName &S : SectionNames) 1439 if (SectionAmountMap[S.Name] > 1) 1440 S.IsNameUnique = false; 1441 } 1442 1443 Optional<RelocAddrEntry> find(const DWARFSection &S, 1444 uint64_t Pos) const override { 1445 auto &Sec = static_cast<const DWARFSectionMap &>(S); 1446 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos); 1447 if (AI == Sec.Relocs.end()) 1448 return None; 1449 return AI->second; 1450 } 1451 1452 const object::ObjectFile *getFile() const override { return Obj; } 1453 1454 ArrayRef<SectionName> getSectionNames() const override { 1455 return SectionNames; 1456 } 1457 1458 bool isLittleEndian() const override { return IsLittleEndian; } 1459 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; } 1460 const DWARFSection &getLineDWOSection() const override { 1461 return LineDWOSection; 1462 } 1463 const DWARFSection &getLocDWOSection() const override { 1464 return LocDWOSection; 1465 } 1466 StringRef getStringDWOSection() const override { return StringDWOSection; } 1467 const DWARFSection &getStringOffsetDWOSection() const override { 1468 return StringOffsetDWOSection; 1469 } 1470 const DWARFSection &getRangeDWOSection() const override { 1471 return RangeDWOSection; 1472 } 1473 const DWARFSection &getAddrSection() const override { return AddrSection; } 1474 StringRef getCUIndexSection() const override { return CUIndexSection; } 1475 StringRef getGdbIndexSection() const override { return GdbIndexSection; } 1476 StringRef getTUIndexSection() const override { return TUIndexSection; } 1477 1478 // DWARF v5 1479 const DWARFSection &getStringOffsetSection() const override { 1480 return StringOffsetSection; 1481 } 1482 StringRef getLineStringSection() const override { return LineStringSection; } 1483 1484 // Sections for DWARF5 split dwarf proposal. 1485 const DWARFSection &getInfoDWOSection() const override { 1486 return InfoDWOSection; 1487 } 1488 void forEachTypesDWOSections( 1489 function_ref<void(const DWARFSection &)> F) const override { 1490 for (auto &P : TypesDWOSections) 1491 F(P.second); 1492 } 1493 1494 StringRef getAbbrevSection() const override { return AbbrevSection; } 1495 const DWARFSection &getLocSection() const override { return LocSection; } 1496 StringRef getARangeSection() const override { return ARangeSection; } 1497 StringRef getDebugFrameSection() const override { return DebugFrameSection; } 1498 StringRef getEHFrameSection() const override { return EHFrameSection; } 1499 const DWARFSection &getLineSection() const override { return LineSection; } 1500 StringRef getStringSection() const override { return StringSection; } 1501 const DWARFSection &getRangeSection() const override { return RangeSection; } 1502 const DWARFSection &getRnglistsSection() const override { 1503 return RnglistsSection; 1504 } 1505 StringRef getMacinfoSection() const override { return MacinfoSection; } 1506 StringRef getPubNamesSection() const override { return PubNamesSection; } 1507 StringRef getPubTypesSection() const override { return PubTypesSection; } 1508 StringRef getGnuPubNamesSection() const override { 1509 return GnuPubNamesSection; 1510 } 1511 StringRef getGnuPubTypesSection() const override { 1512 return GnuPubTypesSection; 1513 } 1514 const DWARFSection &getAppleNamesSection() const override { 1515 return AppleNamesSection; 1516 } 1517 const DWARFSection &getAppleTypesSection() const override { 1518 return AppleTypesSection; 1519 } 1520 const DWARFSection &getAppleNamespacesSection() const override { 1521 return AppleNamespacesSection; 1522 } 1523 const DWARFSection &getAppleObjCSection() const override { 1524 return AppleObjCSection; 1525 } 1526 const DWARFSection &getDebugNamesSection() const override { 1527 return DebugNamesSection; 1528 } 1529 1530 StringRef getFileName() const override { return FileName; } 1531 uint8_t getAddressSize() const override { return AddressSize; } 1532 const DWARFSection &getInfoSection() const override { return InfoSection; } 1533 void forEachTypesSections( 1534 function_ref<void(const DWARFSection &)> F) const override { 1535 for (auto &P : TypesSections) 1536 F(P.second); 1537 } 1538 }; 1539 } // namespace 1540 1541 std::unique_ptr<DWARFContext> 1542 DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L, 1543 function_ref<ErrorPolicy(Error)> HandleError, 1544 std::string DWPName) { 1545 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError); 1546 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName)); 1547 } 1548 1549 std::unique_ptr<DWARFContext> 1550 DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections, 1551 uint8_t AddrSize, bool isLittleEndian) { 1552 auto DObj = 1553 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian); 1554 return llvm::make_unique<DWARFContext>(std::move(DObj), ""); 1555 } 1556 1557 Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) { 1558 // Detect the architecture from the object file. We usually don't need OS 1559 // info to lookup a target and create register info. 1560 Triple TT; 1561 TT.setArch(Triple::ArchType(Obj.getArch())); 1562 TT.setVendor(Triple::UnknownVendor); 1563 TT.setOS(Triple::UnknownOS); 1564 std::string TargetLookupError; 1565 const Target *TheTarget = 1566 TargetRegistry::lookupTarget(TT.str(), TargetLookupError); 1567 if (!TargetLookupError.empty()) 1568 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode()); 1569 RegInfo.reset(TheTarget->createMCRegInfo(TT.str())); 1570 return Error::success(); 1571 } 1572