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