LCOV - code coverage report
Current view: top level - lib/DebugInfo/DWARF - DWARFUnit.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 323 337 95.8 %
Date: 2018-07-13 00:08:38 Functions: 32 32 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- DWARFUnit.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/DWARFUnit.h"
      11             : #include "llvm/ADT/SmallString.h"
      12             : #include "llvm/ADT/StringRef.h"
      13             : #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
      14             : #include "llvm/DebugInfo/DWARF/DWARFContext.h"
      15             : #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
      16             : #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
      17             : #include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
      18             : #include "llvm/DebugInfo/DWARF/DWARFDie.h"
      19             : #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
      20             : #include "llvm/Support/DataExtractor.h"
      21             : #include "llvm/Support/Path.h"
      22             : #include "llvm/Support/WithColor.h"
      23             : #include <algorithm>
      24             : #include <cassert>
      25             : #include <cstddef>
      26             : #include <cstdint>
      27             : #include <cstdio>
      28             : #include <utility>
      29             : #include <vector>
      30             : 
      31             : using namespace llvm;
      32             : using namespace dwarf;
      33             : 
      34        4040 : void DWARFUnitSectionBase::parse(DWARFContext &C, const DWARFSection &Section) {
      35             :   const DWARFObject &D = C.getDWARFObj();
      36       16160 :   parseImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangeSection(),
      37        8080 :             D.getStringSection(), D.getStringOffsetSection(),
      38       12120 :             &D.getAddrSection(), D.getLineSection(), D.isLittleEndian(), false,
      39        4040 :             false);
      40        4040 : }
      41             : 
      42         761 : void DWARFUnitSectionBase::parseDWO(DWARFContext &C,
      43             :                                     const DWARFSection &DWOSection, bool Lazy) {
      44             :   const DWARFObject &D = C.getDWARFObj();
      45        3805 :   parseImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangeDWOSection(),
      46        1522 :             D.getStringDWOSection(), D.getStringOffsetDWOSection(),
      47        1522 :             &D.getAddrSection(), D.getLineDWOSection(), C.isLittleEndian(),
      48         761 :             true, Lazy);
      49         761 : }
      50             : 
      51        5125 : DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
      52             :                      const DWARFUnitHeader &Header,
      53             :                      const DWARFDebugAbbrev *DA, const DWARFSection *RS,
      54             :                      StringRef SS, const DWARFSection &SOS,
      55             :                      const DWARFSection *AOS, const DWARFSection &LS, bool LE,
      56        5125 :                      bool IsDWO, const DWARFUnitSectionBase &UnitSection)
      57             :     : Context(DC), InfoSection(Section), Header(Header), Abbrev(DA),
      58             :       RangeSection(RS), LineSection(LS), StringSection(SS),
      59             :       StringOffsetSection(SOS),  AddrOffsetSection(AOS), isLittleEndian(LE),
      60       10250 :       isDWO(IsDWO), UnitSection(UnitSection) {
      61        5125 :   clear();
      62        5125 : }
      63             : 
      64             : DWARFUnit::~DWARFUnit() = default;
      65             : 
      66       73418 : DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {
      67      146836 :   return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, isLittleEndian,
      68      146836 :                             getAddressByteSize());
      69             : }
      70             : 
      71         106 : bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
      72             :                                                 uint64_t &Result) const {
      73         212 :   uint32_t Offset = AddrOffsetSectionBase + Index * getAddressByteSize();
      74         212 :   if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
      75             :     return false;
      76          91 :   DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
      77          91 :                         isLittleEndian, getAddressByteSize());
      78          91 :   Result = DA.getRelocatedAddress(&Offset);
      79          91 :   return true;
      80             : }
      81             : 
      82        1077 : bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index,
      83             :                                            uint64_t &Result) const {
      84        1077 :   if (!StringOffsetsTableContribution)
      85             :     return false;
      86        1076 :   unsigned ItemSize = getDwarfStringOffsetsByteSize();
      87        1076 :   uint32_t Offset = getStringOffsetsBase() + Index * ItemSize;
      88        2152 :   if (StringOffsetSection.Data.size() < Offset + ItemSize)
      89             :     return false;
      90        1076 :   DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
      91        1076 :                         isLittleEndian, 0);
      92        1076 :   Result = DA.getRelocatedValue(ItemSize, &Offset);
      93        1076 :   return true;
      94             : }
      95             : 
      96        5154 : bool DWARFUnitHeader::extract(DWARFContext &Context,
      97             :                               const DWARFDataExtractor &debug_info,
      98             :                               uint32_t *offset_ptr,
      99             :                               DWARFSectionKind SectionKind,
     100             :                               const DWARFUnitIndex *Index) {
     101        5154 :   Offset = *offset_ptr;
     102        5154 :   IndexEntry = Index ? Index->getFromOffset(*offset_ptr) : nullptr;
     103        5154 :   Length = debug_info.getU32(offset_ptr);
     104             :   // FIXME: Support DWARF64.
     105             :   unsigned SizeOfLength = 4;
     106        5154 :   FormParams.Format = DWARF32;
     107        5154 :   FormParams.Version = debug_info.getU16(offset_ptr);
     108        5154 :   if (FormParams.Version >= 5) {
     109          81 :     UnitType = debug_info.getU8(offset_ptr);
     110          81 :     FormParams.AddrSize = debug_info.getU8(offset_ptr);
     111          81 :     AbbrOffset = debug_info.getU32(offset_ptr);
     112             :   } else {
     113        5073 :     AbbrOffset = debug_info.getRelocatedValue(4, offset_ptr);
     114        5073 :     FormParams.AddrSize = debug_info.getU8(offset_ptr);
     115             :     // Fake a unit type based on the section type.  This isn't perfect,
     116             :     // but distinguishing compile and type units is generally enough.
     117        5073 :     if (SectionKind == DW_SECT_TYPES)
     118          45 :       UnitType = DW_UT_type;
     119             :     else
     120        5028 :       UnitType = DW_UT_compile;
     121             :   }
     122        5154 :   if (IndexEntry) {
     123          37 :     if (AbbrOffset)
     124             :       return false;
     125          37 :     auto *UnitContrib = IndexEntry->getOffset();
     126          37 :     if (!UnitContrib || UnitContrib->Length != (Length + 4))
     127             :       return false;
     128          37 :     auto *AbbrEntry = IndexEntry->getOffset(DW_SECT_ABBREV);
     129          37 :     if (!AbbrEntry)
     130             :       return false;
     131          37 :     AbbrOffset = AbbrEntry->Offset;
     132             :   }
     133       10308 :   if (isTypeUnit()) {
     134          59 :     TypeHash = debug_info.getU64(offset_ptr);
     135          59 :     TypeOffset = debug_info.getU32(offset_ptr);
     136        5095 :   } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)
     137           8 :     DWOId = debug_info.getU64(offset_ptr);
     138             : 
     139             :   // Header fields all parsed, capture the size of this unit header.
     140             :   assert(*offset_ptr - Offset <= 255 && "unexpected header size");
     141        5154 :   Size = uint8_t(*offset_ptr - Offset);
     142             : 
     143             :   // Type offset is unit-relative; should be after the header and before
     144             :   // the end of the current unit.
     145             :   bool TypeOffsetOK =
     146        5154 :       !isTypeUnit()
     147        5154 :           ? true
     148          59 :           : TypeOffset >= Size && TypeOffset < getLength() + SizeOfLength;
     149       10308 :   bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
     150        5154 :   bool VersionOK = DWARFContext::isSupportedVersion(getVersion());
     151        5154 :   bool AddrSizeOK = getAddressByteSize() == 4 || getAddressByteSize() == 8;
     152             : 
     153        5154 :   if (!LengthOK || !VersionOK || !AddrSizeOK || !TypeOffsetOK)
     154             :     return false;
     155             : 
     156             :   // Keep track of the highest DWARF version we encounter across all units.
     157             :   Context.setMaxVersionIfGreater(getVersion());
     158             :   return true;
     159             : }
     160             : 
     161             : // Parse the rangelist table header, including the optional array of offsets
     162             : // following it (DWARF v5 and later).
     163             : static Expected<DWARFDebugRnglistTable>
     164          78 : parseRngListTableHeader(DWARFDataExtractor &DA, uint32_t Offset) {
     165             :   // TODO: Support DWARF64
     166             :   // We are expected to be called with Offset 0 or pointing just past the table
     167             :   // header, which is 12 bytes long for DWARF32.
     168          78 :   if (Offset > 0) {
     169           8 :     if (Offset < 12U) {
     170             :       std::string Buffer;
     171           2 :       raw_string_ostream Stream(Buffer);
     172           2 :       Stream << format(
     173             :           "Did not detect a valid range list table with base = 0x%x", Offset);
     174           4 :       return make_error<StringError>(Stream.str(), inconvertibleErrorCode());
     175             :     }
     176           6 :     Offset -= 12U;
     177             :   }
     178          76 :   llvm::DWARFDebugRnglistTable Table;
     179         152 :   if (Error E = Table.extractHeaderAndOffsets(DA, &Offset))
     180             :     return std::move(E);
     181             :   return Table;
     182             : }
     183             : 
     184        1164 : Error DWARFUnit::extractRangeList(uint32_t RangeListOffset,
     185             :                                   DWARFDebugRangeList &RangeList) const {
     186             :   // Require that compile unit is extracted.
     187             :   assert(!DieArray.empty());
     188        1164 :   DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
     189        1164 :                                 isLittleEndian, getAddressByteSize());
     190        1164 :   uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
     191        1164 :   return RangeList.extract(RangesData, &ActualRangeListOffset);
     192             : }
     193             : 
     194        5125 : void DWARFUnit::clear() {
     195        5125 :   Abbrevs = nullptr;
     196             :   BaseAddr.reset();
     197        5125 :   RangeSectionBase = 0;
     198        5125 :   AddrOffsetSectionBase = 0;
     199        5125 :   clearDIEs(false);
     200             :   DWO.reset();
     201        5125 : }
     202             : 
     203        3531 : const char *DWARFUnit::getCompilationDir() {
     204        7062 :   return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
     205             : }
     206             : 
     207        4605 : void DWARFUnit::extractDIEsToVector(
     208             :     bool AppendCUDie, bool AppendNonCUDies,
     209             :     std::vector<DWARFDebugInfoEntry> &Dies) const {
     210        4605 :   if (!AppendCUDie && !AppendNonCUDies)
     211           0 :     return;
     212             : 
     213             :   // Set the offset to that of the first DIE and calculate the start of the
     214             :   // next compilation unit header.
     215        4605 :   uint32_t DIEOffset = getOffset() + getHeaderSize();
     216             :   uint32_t NextCUOffset = getNextUnitOffset();
     217        4605 :   DWARFDebugInfoEntry DIE;
     218        4605 :   DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
     219             :   uint32_t Depth = 0;
     220             :   bool IsCUDie = true;
     221             : 
     222       38685 :   while (DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
     223             :                          Depth)) {
     224       38019 :     if (IsCUDie) {
     225        4595 :       if (AppendCUDie)
     226        3846 :         Dies.push_back(DIE);
     227        4595 :       if (!AppendNonCUDies)
     228             :         break;
     229             :       // The average bytes per DIE entry has been seen to be
     230             :       // around 14-20 so let's pre-reserve the needed memory for
     231             :       // our DIE entries accordingly.
     232        4260 :       Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
     233             :       IsCUDie = false;
     234             :     } else {
     235       33424 :       Dies.push_back(DIE);
     236             :     }
     237             : 
     238       35554 :     if (const DWARFAbbreviationDeclaration *AbbrDecl =
     239       35554 :             DIE.getAbbreviationDeclarationPtr()) {
     240             :       // Normal DIE
     241       28544 :       if (AbbrDecl->hasChildren())
     242        6988 :         ++Depth;
     243             :     } else {
     244             :       // NULL DIE.
     245        7010 :       if (Depth > 0)
     246        6985 :         --Depth;
     247        7010 :       if (Depth == 0)
     248             :         break;  // We are done with this compile unit!
     249             :     }
     250             :   }
     251             : 
     252             :   // Give a little bit of info if we encounter corrupt DWARF (our offset
     253             :   // should always terminate at or before the start of the next compilation
     254             :   // unit header).
     255        4605 :   if (DIEOffset > NextCUOffset)
     256          15 :     WithColor::warning() << format("DWARF compile unit extends beyond its "
     257             :                                    "bounds cu 0x%8.8x at 0x%8.8x\n",
     258             :                                    getOffset(), DIEOffset);
     259             : }
     260             : 
     261       29984 : size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
     262       62436 :   if ((CUDieOnly && !DieArray.empty()) ||
     263       14193 :       DieArray.size() > 1)
     264             :     return 0; // Already parsed.
     265             : 
     266             :   bool HasCUDie = !DieArray.empty();
     267        4605 :   extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
     268             : 
     269        4605 :   if (DieArray.empty())
     270             :     return 0;
     271             : 
     272             :   // If CU DIE was just parsed, copy several attribute values from it.
     273        4595 :   if (!HasCUDie) {
     274        3846 :     DWARFDie UnitDie = getUnitDIE();
     275        7692 :     if (Optional<uint64_t> DWOId = toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id)))
     276         175 :       Header.setDWOId(*DWOId);
     277        3846 :     if (!isDWO) {
     278             :       assert(AddrOffsetSectionBase == 0);
     279             :       assert(RangeSectionBase == 0);
     280        3743 :       AddrOffsetSectionBase =
     281        7486 :           toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base), 0);
     282        7486 :       RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
     283             :     }
     284             : 
     285             :     // In general, in DWARF v5 and beyond we derive the start of the unit's
     286             :     // contribution to the string offsets table from the unit DIE's
     287             :     // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
     288             :     // attribute, so we assume that there is a contribution to the string
     289             :     // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
     290             :     // In both cases we need to determine the format of the contribution,
     291             :     // which may differ from the unit's format.
     292             :     uint64_t StringOffsetsContributionBase =
     293        7692 :         isDWO ? 0 : toSectionOffset(UnitDie.find(DW_AT_str_offsets_base), 0);
     294        3846 :     auto IndexEntry = Header.getIndexEntry();
     295        3846 :     if (IndexEntry)
     296          37 :       if (const auto *C = IndexEntry->getOffset(DW_SECT_STR_OFFSETS))
     297          34 :         StringOffsetsContributionBase += C->Offset;
     298             : 
     299        3846 :     DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
     300        3846 :                           isLittleEndian, 0);
     301        3846 :     if (isDWO)
     302             :       StringOffsetsTableContribution =
     303         206 :           determineStringOffsetsTableContributionDWO(
     304             :               DA, StringOffsetsContributionBase);
     305        3743 :     else if (getVersion() >= 5)
     306         122 :       StringOffsetsTableContribution = determineStringOffsetsTableContribution(
     307             :           DA, StringOffsetsContributionBase);
     308             : 
     309             :     // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to
     310             :     // describe address ranges.
     311        3846 :     if (getVersion() >= 5) {
     312          78 :       if (isDWO)
     313          34 :         setRangesSection(&Context.getDWARFObj().getRnglistsDWOSection(), 0);
     314             :       else
     315         122 :         setRangesSection(&Context.getDWARFObj().getRnglistsSection(),
     316         122 :                          toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0));
     317             :       // Parse the range list table header. Individual range lists are
     318             :       // extracted lazily.
     319          78 :       DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
     320          78 :                                   isLittleEndian, 0);
     321          78 :       if (auto TableOrError =
     322         156 :               parseRngListTableHeader(RangesDA, RangeSectionBase))
     323             :         RngListTable = TableOrError.get();
     324             :       else
     325          71 :         WithColor::error() << "parsing a range list table: "
     326         213 :                            << toString(TableOrError.takeError())
     327             :                            << '\n';
     328             : 
     329             :       // In a split dwarf unit, there is no DW_AT_rnglists_base attribute.
     330             :       // Adjust RangeSectionBase to point past the table header.
     331          78 :       if (isDWO && RngListTable)
     332           2 :         RangeSectionBase = RngListTable->getHeaderSize();
     333             :     }
     334             : 
     335             :     // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
     336             :     // skeleton CU DIE, so that DWARF users not aware of it are not broken.
     337             :   }
     338             : 
     339        9190 :   return DieArray.size();
     340             : }
     341             : 
     342        1264 : bool DWARFUnit::parseDWO() {
     343        1264 :   if (isDWO)
     344             :     return false;
     345        1259 :   if (DWO.get())
     346             :     return false;
     347        1256 :   DWARFDie UnitDie = getUnitDIE();
     348             :   if (!UnitDie)
     349             :     return false;
     350        2512 :   auto DWOFileName = dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
     351        1256 :   if (!DWOFileName)
     352             :     return false;
     353          64 :   auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
     354             :   SmallString<16> AbsolutePath;
     355          96 :   if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
     356          32 :       *CompilationDir) {
     357          32 :     sys::path::append(AbsolutePath, *CompilationDir);
     358             :   }
     359          64 :   sys::path::append(AbsolutePath, *DWOFileName);
     360             :   auto DWOId = getDWOId();
     361          32 :   if (!DWOId)
     362             :     return false;
     363          64 :   auto DWOContext = Context.getDWOContext(AbsolutePath);
     364          32 :   if (!DWOContext)
     365             :     return false;
     366             : 
     367          19 :   DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
     368          19 :   if (!DWOCU)
     369             :     return false;
     370             :   DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
     371             :   // Share .debug_addr and .debug_ranges section with compile unit in .dwo
     372          19 :   DWO->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
     373          19 :   if (getVersion() >= 5) {
     374           0 :     DWO->setRangesSection(&Context.getDWARFObj().getRnglistsDWOSection(), 0);
     375           0 :     DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
     376           0 :                                 isLittleEndian, 0);
     377           0 :     if (auto TableOrError = parseRngListTableHeader(RangesDA, RangeSectionBase))
     378             :       DWO->RngListTable = TableOrError.get();
     379             :     else
     380           0 :       WithColor::error() << "parsing a range list table: "
     381           0 :                          << toString(TableOrError.takeError())
     382             :                          << '\n';
     383           0 :     if (DWO->RngListTable)
     384           0 :       DWO->RangeSectionBase = DWO->RngListTable->getHeaderSize();
     385             :   } else {
     386          19 :     auto DWORangesBase = UnitDie.getRangesBaseAttribute();
     387          19 :     DWO->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0);
     388             :   }
     389             : 
     390             :   return true;
     391             : }
     392             : 
     393        5145 : void DWARFUnit::clearDIEs(bool KeepCUDie) {
     394       10290 :   if (DieArray.size() > (unsigned)KeepCUDie) {
     395          20 :     DieArray.resize((unsigned)KeepCUDie);
     396             :     DieArray.shrink_to_fit();
     397             :   }
     398        5145 : }
     399             : 
     400             : Expected<DWARFAddressRangesVector>
     401        1172 : DWARFUnit::findRnglistFromOffset(uint32_t Offset) {
     402        1172 :   if (getVersion() <= 4) {
     403             :     DWARFDebugRangeList RangeList;
     404        2328 :     if (Error E = extractRangeList(Offset, RangeList))
     405             :       return std::move(E);
     406        2320 :     return RangeList.getAbsoluteRanges(getBaseAddress());
     407             :   }
     408           8 :   if (RngListTable) {
     409           7 :     DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
     410           7 :                                   isLittleEndian, RngListTable->getAddrSize());
     411          14 :     auto RangeListOrError = RngListTable->findRangeList(RangesData, Offset);
     412           7 :     if (RangeListOrError)
     413          10 :       return RangeListOrError.get().getAbsoluteRanges(getBaseAddress());
     414             :     return RangeListOrError.takeError();
     415             :   }
     416             : 
     417             :   return make_error<StringError>("missing or invalid range list table",
     418           2 :                                  inconvertibleErrorCode());
     419             : }
     420             : 
     421             : Expected<DWARFAddressRangesVector>
     422           5 : DWARFUnit::findRnglistFromIndex(uint32_t Index) {
     423           5 :   if (auto Offset = getRnglistOffset(Index))
     424           3 :     return findRnglistFromOffset(*Offset + RangeSectionBase);
     425             : 
     426             :   std::string Buffer;
     427           2 :   raw_string_ostream Stream(Buffer);
     428           2 :   if (RngListTable)
     429           0 :     Stream << format("invalid range list table index %d", Index);
     430             :   else
     431           2 :     Stream << "missing or invalid range list table";
     432           4 :   return make_error<StringError>(Stream.str(), inconvertibleErrorCode());
     433             : }
     434             : 
     435        2328 : void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
     436        2328 :   DWARFDie UnitDie = getUnitDIE();
     437             :   if (!UnitDie)
     438        1786 :     return;
     439             :   // First, check if unit DIE describes address ranges for the whole unit.
     440        2870 :   auto CUDIERangesOrError = UnitDie.getAddressRanges();
     441        2328 :   if (CUDIERangesOrError) {
     442        2326 :     if (!CUDIERangesOrError.get().empty()) {
     443        1786 :       CURanges.insert(CURanges.end(), CUDIERangesOrError.get().begin(),
     444        1786 :                       CUDIERangesOrError.get().end());
     445        1786 :       return;
     446             :     }
     447             :   } else
     448           2 :     WithColor::error() << "decoding address ranges: "
     449           6 :                        << toString(CUDIERangesOrError.takeError()) << '\n';
     450             : 
     451             :   // This function is usually called if there in no .debug_aranges section
     452             :   // in order to produce a compile unit level set of address ranges that
     453             :   // is accurate. If the DIEs weren't parsed, then we don't want all dies for
     454             :   // all compile units to stay loaded when they weren't needed. So we can end
     455             :   // up parsing the DWARF and then throwing them all away to keep memory usage
     456             :   // down.
     457         542 :   const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
     458         542 :   getUnitDIE().collectChildrenAddressRanges(CURanges);
     459             : 
     460             :   // Collect address ranges from DIEs in .dwo if necessary.
     461         542 :   bool DWOCreated = parseDWO();
     462         542 :   if (DWO)
     463           5 :     DWO->collectAddressRanges(CURanges);
     464         542 :   if (DWOCreated)
     465             :     DWO.reset();
     466             : 
     467             :   // Keep memory down by clearing DIEs if this generate function
     468             :   // caused them to be parsed.
     469         542 :   if (ClearDIEs)
     470          20 :     clearDIEs(true);
     471             : }
     472             : 
     473       21987 : void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
     474       21987 :   if (Die.isSubroutineDIE()) {
     475        7224 :     auto DIERangesOrError = Die.getAddressRanges();
     476        3612 :     if (DIERangesOrError) {
     477        3936 :       for (const auto &R : DIERangesOrError.get()) {
     478             :         // Ignore 0-sized ranges.
     479         324 :         if (R.LowPC == R.HighPC)
     480             :           continue;
     481             :         auto B = AddrDieMap.upper_bound(R.LowPC);
     482         501 :         if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
     483             :           // The range is a sub-range of existing ranges, we need to split the
     484             :           // existing range.
     485          59 :           if (R.HighPC < B->second.first)
     486          56 :             AddrDieMap[R.HighPC] = B->second;
     487          59 :           if (R.LowPC > B->first)
     488          30 :             AddrDieMap[B->first].first = R.LowPC;
     489             :         }
     490         648 :         AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
     491             :       }
     492             :     } else
     493           0 :       llvm::consumeError(DIERangesOrError.takeError());
     494             :   }
     495             :   // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
     496             :   // simplify the logic to update AddrDieMap. The child's range will always
     497             :   // be equal or smaller than the parent's range. With this assumption, when
     498             :   // adding one range into the map, it will at most split a range into 3
     499             :   // sub-ranges.
     500       43815 :   for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
     501       21828 :     updateAddressDieMap(Child);
     502       21987 : }
     503             : 
     504         725 : DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
     505         725 :   extractDIEsIfNeeded(false);
     506         725 :   if (AddrDieMap.empty())
     507         159 :     updateAddressDieMap(getUnitDIE());
     508             :   auto R = AddrDieMap.upper_bound(Address);
     509         725 :   if (R == AddrDieMap.begin())
     510          26 :     return DWARFDie();
     511             :   // upper_bound's previous item contains Address.
     512             :   --R;
     513         699 :   if (Address >= R->second.first)
     514           5 :     return DWARFDie();
     515         694 :   return R->second.second;
     516             : }
     517             : 
     518             : void
     519         722 : DWARFUnit::getInlinedChainForAddress(uint64_t Address,
     520             :                                      SmallVectorImpl<DWARFDie> &InlinedChain) {
     521             :   assert(InlinedChain.empty());
     522             :   // Try to look for subprogram DIEs in the DWO file.
     523         722 :   parseDWO();
     524             :   // First, find the subroutine that contains the given address (the leaf
     525             :   // of inlined chain).
     526             :   DWARFDie SubroutineDIE =
     527         722 :       (DWO ? DWO.get() : this)->getSubroutineForAddress(Address);
     528             : 
     529             :   if (!SubroutineDIE)
     530          31 :     return;
     531             : 
     532          61 :   while (!SubroutineDIE.isSubprogramDIE()) {
     533          61 :     if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
     534          55 :       InlinedChain.push_back(SubroutineDIE);
     535          61 :     SubroutineDIE  = SubroutineDIE.getParent();
     536             :   }
     537         691 :   InlinedChain.push_back(SubroutineDIE);
     538             : }
     539             : 
     540         705 : const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
     541             :                                               DWARFSectionKind Kind) {
     542         705 :   if (Kind == DW_SECT_INFO)
     543         692 :     return Context.getCUIndex();
     544             :   assert(Kind == DW_SECT_TYPES);
     545          13 :   return Context.getTUIndex();
     546             : }
     547             : 
     548          76 : DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
     549          76 :   if (!Die)
     550           0 :     return DWARFDie();
     551          76 :   const uint32_t Depth = Die->getDepth();
     552             :   // Unit DIEs always have a depth of zero and never have parents.
     553          76 :   if (Depth == 0)
     554           5 :     return DWARFDie();
     555             :   // Depth of 1 always means parent is the compile/type unit.
     556          71 :   if (Depth == 1)
     557             :     return getUnitDIE();
     558             :   // Look for previous DIE with a depth that is one less than the Die's depth.
     559          66 :   const uint32_t ParentDepth = Depth - 1;
     560          88 :   for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) {
     561         176 :     if (DieArray[I].getDepth() == ParentDepth)
     562          66 :       return DWARFDie(this, &DieArray[I]);
     563             :   }
     564           0 :   return DWARFDie();
     565             : }
     566             : 
     567       34396 : DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
     568       34396 :   if (!Die)
     569           0 :     return DWARFDie();
     570       34396 :   uint32_t Depth = Die->getDepth();
     571             :   // Unit DIEs always have a depth of zero and never have siblings.
     572       34396 :   if (Depth == 0)
     573           1 :     return DWARFDie();
     574             :   // NULL DIEs don't have siblings.
     575       34395 :   if (Die->getAbbreviationDeclarationPtr() == nullptr)
     576        5769 :     return DWARFDie();
     577             : 
     578             :   // Find the next DIE whose depth is the same as the Die's depth.
     579      104358 :   for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
     580             :        ++I) {
     581       52178 :     if (DieArray[I].getDepth() == Depth)
     582       28625 :       return DWARFDie(this, &DieArray[I]);
     583             :   }
     584           1 :   return DWARFDie();
     585             : }
     586             : 
     587       32297 : DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {
     588       32297 :   if (!Die->hasChildren())
     589       24368 :     return DWARFDie();
     590             : 
     591             :   // We do not want access out of bounds when parsing corrupted debug data.
     592        7929 :   size_t I = getDIEIndex(Die) + 1;
     593       15858 :   if (I >= DieArray.size())
     594           1 :     return DWARFDie();
     595        7928 :   return DWARFDie(this, &DieArray[I]);
     596             : }
     597             : 
     598       31705 : const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {
     599       31705 :   if (!Abbrevs)
     600        3845 :     Abbrevs = Abbrev->getAbbreviationDeclarationSet(Header.getAbbrOffset());
     601       31705 :   return Abbrevs;
     602             : }
     603             : 
     604        1323 : llvm::Optional<BaseAddress> DWARFUnit::getBaseAddress() {
     605        1323 :   if (BaseAddr)
     606             :     return BaseAddr;
     607             : 
     608        1234 :   DWARFDie UnitDie = getUnitDIE();
     609        1234 :   Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});
     610        1234 :   if (Optional<uint64_t> Addr = toAddress(PC))
     611        1223 :     BaseAddr = {*Addr, PC->getSectionIndex()};
     612             : 
     613             :   return BaseAddr;
     614             : }
     615             : 
     616             : Optional<StrOffsetsContributionDescriptor>
     617          47 : StrOffsetsContributionDescriptor::validateContributionSize(
     618             :     DWARFDataExtractor &DA) {
     619             :   uint8_t EntrySize = getDwarfOffsetByteSize();
     620             :   // In order to ensure that we don't read a partial record at the end of
     621             :   // the section we validate for a multiple of the entry size.
     622          47 :   uint64_t ValidationSize = alignTo(Size, EntrySize);
     623             :   // Guard against overflow.
     624          47 :   if (ValidationSize >= Size)
     625          47 :     if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
     626             :       return *this;
     627             :   return Optional<StrOffsetsContributionDescriptor>();
     628             : }
     629             : 
     630             : // Look for a DWARF64-formatted contribution to the string offsets table
     631             : // starting at a given offset and record it in a descriptor.
     632             : static Optional<StrOffsetsContributionDescriptor>
     633          22 : parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint32_t Offset) {
     634          22 :   if (!DA.isValidOffsetForDataOfSize(Offset, 16))
     635             :     return Optional<StrOffsetsContributionDescriptor>();
     636             : 
     637          19 :   if (DA.getU32(&Offset) != 0xffffffff)
     638             :     return Optional<StrOffsetsContributionDescriptor>();
     639             : 
     640           2 :   uint64_t Size = DA.getU64(&Offset);
     641           2 :   uint8_t Version = DA.getU16(&Offset);
     642           2 :   (void)DA.getU16(&Offset); // padding
     643             :   // The encoded length includes the 2-byte version field and the 2-byte
     644             :   // padding, so we need to subtract them out when we populate the descriptor.
     645           2 :   return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);
     646             :   //return Optional<StrOffsetsContributionDescriptor>(Descriptor);
     647             : }
     648             : 
     649             : // Look for a DWARF32-formatted contribution to the string offsets table
     650             : // starting at a given offset and record it in a descriptor.
     651             : static Optional<StrOffsetsContributionDescriptor>
     652          49 : parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint32_t Offset) {
     653          49 :   if (!DA.isValidOffsetForDataOfSize(Offset, 8))
     654             :     return Optional<StrOffsetsContributionDescriptor>();
     655          46 :   uint32_t ContributionSize = DA.getU32(&Offset);
     656          46 :   if (ContributionSize >= 0xfffffff0)
     657             :     return Optional<StrOffsetsContributionDescriptor>();
     658          45 :   uint8_t Version = DA.getU16(&Offset);
     659          45 :   (void)DA.getU16(&Offset); // padding
     660             :   // The encoded length includes the 2-byte version field and the 2-byte
     661             :   // padding, so we need to subtract them out when we populate the descriptor.
     662          45 :   return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,
     663             :                                           DWARF32);
     664             :   //return Optional<StrOffsetsContributionDescriptor>(Descriptor);
     665             : }
     666             : 
     667             : Optional<StrOffsetsContributionDescriptor>
     668          61 : DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA,
     669             :                                                    uint64_t Offset) {
     670             :   Optional<StrOffsetsContributionDescriptor> Descriptor;
     671             :   // Attempt to find a DWARF64 contribution 16 bytes before the base.
     672          61 :   if (Offset >= 16)
     673             :     Descriptor =
     674          10 :         parseDWARF64StringOffsetsTableHeader(DA, (uint32_t)Offset - 16);
     675             :   // Try to find a DWARF32 contribution 8 bytes before the base.
     676          61 :   if (!Descriptor && Offset >= 8)
     677          64 :     Descriptor = parseDWARF32StringOffsetsTableHeader(DA, (uint32_t)Offset - 8);
     678         122 :   return Descriptor ? Descriptor->validateContributionSize(DA) : Descriptor;
     679             : }
     680             : 
     681             : Optional<StrOffsetsContributionDescriptor>
     682         103 : DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor &DA,
     683             :                                                       uint64_t Offset) {
     684         103 :   if (getVersion() >= 5) {
     685             :     // Look for a valid contribution at the given offset.
     686             :     auto Descriptor =
     687          17 :         parseDWARF64StringOffsetsTableHeader(DA, (uint32_t)Offset);
     688          17 :     if (!Descriptor)
     689          34 :       Descriptor = parseDWARF32StringOffsetsTableHeader(DA, (uint32_t)Offset);
     690          17 :     return Descriptor ? Descriptor->validateContributionSize(DA) : Descriptor;
     691             :   }
     692             :   // Prior to DWARF v5, we derive the contribution size from the
     693             :   // index table (in a package file). In a .dwo file it is simply
     694             :   // the length of the string offsets section.
     695             :   uint64_t Size = 0;
     696          86 :   auto IndexEntry = Header.getIndexEntry();
     697          86 :   if (!IndexEntry)
     698          53 :     Size = StringOffsetSection.Data.size();
     699          33 :   else if (const auto *C = IndexEntry->getOffset(DW_SECT_STR_OFFSETS))
     700          30 :     Size = C->Length;
     701             :   // Return a descriptor with the given offset as base, version 4 and
     702             :   // DWARF32 format.
     703             :   //return Optional<StrOffsetsContributionDescriptor>(
     704             :       //StrOffsetsContributionDescriptor(Offset, Size, 4, DWARF32));
     705             :   return StrOffsetsContributionDescriptor(Offset, Size, 4, DWARF32);
     706             : }

Generated by: LCOV version 1.13