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