LCOV - code coverage report
Current view: top level - lib/DebugInfo/DWARF - DWARFContext.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 737 755 97.6 %
Date: 2018-05-20 00:06:23 Functions: 103 103 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13