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

Generated by: LCOV version 1.13