1 //===- DWARFUnit.cpp ------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/DebugInfo/DWARF/DWARFUnit.h" 10 #include "llvm/ADT/SmallString.h" 11 #include "llvm/ADT/StringRef.h" 12 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h" 13 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.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/DebugInfo/DWARF/DWARFTypeUnit.h" 21 #include "llvm/Support/DataExtractor.h" 22 #include "llvm/Support/Errc.h" 23 #include "llvm/Support/Path.h" 24 #include <algorithm> 25 #include <cassert> 26 #include <cstddef> 27 #include <cstdint> 28 #include <cstdio> 29 #include <utility> 30 #include <vector> 31 32 using namespace llvm; 33 using namespace dwarf; 34 35 void DWARFUnitVector::addUnitsForSection(DWARFContext &C, 36 const DWARFSection &Section, 37 DWARFSectionKind SectionKind) { 38 const DWARFObject &D = C.getDWARFObj(); 39 addUnitsImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangesSection(), 40 &D.getLocSection(), D.getStrSection(), 41 D.getStrOffsetsSection(), &D.getAddrSection(), 42 D.getLineSection(), D.isLittleEndian(), false, false, 43 SectionKind); 44 } 45 46 void DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C, 47 const DWARFSection &DWOSection, 48 DWARFSectionKind SectionKind, 49 bool Lazy) { 50 const DWARFObject &D = C.getDWARFObj(); 51 addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangesDWOSection(), 52 &D.getLocDWOSection(), D.getStrDWOSection(), 53 D.getStrOffsetsDWOSection(), &D.getAddrSection(), 54 D.getLineDWOSection(), C.isLittleEndian(), true, Lazy, 55 SectionKind); 56 } 57 58 void DWARFUnitVector::addUnitsImpl( 59 DWARFContext &Context, const DWARFObject &Obj, const DWARFSection &Section, 60 const DWARFDebugAbbrev *DA, const DWARFSection *RS, 61 const DWARFSection *LocSection, StringRef SS, const DWARFSection &SOS, 62 const DWARFSection *AOS, const DWARFSection &LS, bool LE, bool IsDWO, 63 bool Lazy, DWARFSectionKind SectionKind) { 64 DWARFDataExtractor Data(Obj, Section, LE, 0); 65 // Lazy initialization of Parser, now that we have all section info. 66 if (!Parser) { 67 Parser = [=, &Context, &Obj, &Section, &SOS, 68 &LS](uint64_t Offset, DWARFSectionKind SectionKind, 69 const DWARFSection *CurSection, 70 const DWARFUnitIndex::Entry *IndexEntry) 71 -> std::unique_ptr<DWARFUnit> { 72 const DWARFSection &InfoSection = CurSection ? *CurSection : Section; 73 DWARFDataExtractor Data(Obj, InfoSection, LE, 0); 74 if (!Data.isValidOffset(Offset)) 75 return nullptr; 76 const DWARFUnitIndex *Index = nullptr; 77 if (IsDWO) 78 Index = &getDWARFUnitIndex(Context, SectionKind); 79 DWARFUnitHeader Header; 80 if (!Header.extract(Context, Data, &Offset, SectionKind, Index, 81 IndexEntry)) 82 return nullptr; 83 std::unique_ptr<DWARFUnit> U; 84 if (Header.isTypeUnit()) 85 U = std::make_unique<DWARFTypeUnit>(Context, InfoSection, Header, DA, 86 RS, LocSection, SS, SOS, AOS, LS, 87 LE, IsDWO, *this); 88 else 89 U = std::make_unique<DWARFCompileUnit>(Context, InfoSection, Header, 90 DA, RS, LocSection, SS, SOS, 91 AOS, LS, LE, IsDWO, *this); 92 return U; 93 }; 94 } 95 if (Lazy) 96 return; 97 // Find a reasonable insertion point within the vector. We skip over 98 // (a) units from a different section, (b) units from the same section 99 // but with lower offset-within-section. This keeps units in order 100 // within a section, although not necessarily within the object file, 101 // even if we do lazy parsing. 102 auto I = this->begin(); 103 uint64_t Offset = 0; 104 while (Data.isValidOffset(Offset)) { 105 if (I != this->end() && 106 (&(*I)->getInfoSection() != &Section || (*I)->getOffset() == Offset)) { 107 ++I; 108 continue; 109 } 110 auto U = Parser(Offset, SectionKind, &Section, nullptr); 111 // If parsing failed, we're done with this section. 112 if (!U) 113 break; 114 Offset = U->getNextUnitOffset(); 115 I = std::next(this->insert(I, std::move(U))); 116 } 117 } 118 119 DWARFUnit *DWARFUnitVector::addUnit(std::unique_ptr<DWARFUnit> Unit) { 120 auto I = std::upper_bound(begin(), end(), Unit, 121 [](const std::unique_ptr<DWARFUnit> &LHS, 122 const std::unique_ptr<DWARFUnit> &RHS) { 123 return LHS->getOffset() < RHS->getOffset(); 124 }); 125 return this->insert(I, std::move(Unit))->get(); 126 } 127 128 DWARFUnit *DWARFUnitVector::getUnitForOffset(uint64_t Offset) const { 129 auto end = begin() + getNumInfoUnits(); 130 auto *CU = 131 std::upper_bound(begin(), end, Offset, 132 [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) { 133 return LHS < RHS->getNextUnitOffset(); 134 }); 135 if (CU != end && (*CU)->getOffset() <= Offset) 136 return CU->get(); 137 return nullptr; 138 } 139 140 DWARFUnit * 141 DWARFUnitVector::getUnitForIndexEntry(const DWARFUnitIndex::Entry &E) { 142 const auto *CUOff = E.getContribution(DW_SECT_INFO); 143 if (!CUOff) 144 return nullptr; 145 146 auto Offset = CUOff->Offset; 147 auto end = begin() + getNumInfoUnits(); 148 149 auto *CU = 150 std::upper_bound(begin(), end, CUOff->Offset, 151 [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) { 152 return LHS < RHS->getNextUnitOffset(); 153 }); 154 if (CU != end && (*CU)->getOffset() <= Offset) 155 return CU->get(); 156 157 if (!Parser) 158 return nullptr; 159 160 auto U = Parser(Offset, DW_SECT_INFO, nullptr, &E); 161 if (!U) 162 U = nullptr; 163 164 auto *NewCU = U.get(); 165 this->insert(CU, std::move(U)); 166 ++NumInfoUnits; 167 return NewCU; 168 } 169 170 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section, 171 const DWARFUnitHeader &Header, const DWARFDebugAbbrev *DA, 172 const DWARFSection *RS, const DWARFSection *LocSection, 173 StringRef SS, const DWARFSection &SOS, 174 const DWARFSection *AOS, const DWARFSection &LS, bool LE, 175 bool IsDWO, const DWARFUnitVector &UnitVector) 176 : Context(DC), InfoSection(Section), Header(Header), Abbrev(DA), 177 RangeSection(RS), LineSection(LS), StringSection(SS), 178 StringOffsetSection(SOS), AddrOffsetSection(AOS), isLittleEndian(LE), 179 IsDWO(IsDWO), UnitVector(UnitVector) { 180 clear(); 181 if (IsDWO) { 182 // If we are reading a package file, we need to adjust the location list 183 // data based on the index entries. 184 StringRef Data = Header.getVersion() >= 5 185 ? Context.getDWARFObj().getLoclistsDWOSection().Data 186 : LocSection->Data; 187 if (auto *IndexEntry = Header.getIndexEntry()) 188 if (const auto *C = IndexEntry->getContribution( 189 Header.getVersion() >= 5 ? DW_SECT_LOCLISTS : DW_SECT_EXT_LOC)) 190 Data = Data.substr(C->Offset, C->Length); 191 192 DWARFDataExtractor DWARFData(Data, isLittleEndian, getAddressByteSize()); 193 LocTable = 194 std::make_unique<DWARFDebugLoclists>(DWARFData, Header.getVersion()); 195 } else if (Header.getVersion() >= 5) { 196 LocTable = std::make_unique<DWARFDebugLoclists>( 197 DWARFDataExtractor(Context.getDWARFObj(), 198 Context.getDWARFObj().getLoclistsSection(), 199 isLittleEndian, getAddressByteSize()), 200 Header.getVersion()); 201 } else { 202 LocTable = std::make_unique<DWARFDebugLoc>( 203 DWARFDataExtractor(Context.getDWARFObj(), *LocSection, isLittleEndian, 204 getAddressByteSize())); 205 } 206 } 207 208 DWARFUnit::~DWARFUnit() = default; 209 210 DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const { 211 return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, isLittleEndian, 212 getAddressByteSize()); 213 } 214 215 Optional<object::SectionedAddress> 216 DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const { 217 if (IsDWO) { 218 auto R = Context.info_section_units(); 219 auto I = R.begin(); 220 // Surprising if a DWO file has more than one skeleton unit in it - this 221 // probably shouldn't be valid, but if a use case is found, here's where to 222 // support it (probably have to linearly search for the matching skeleton CU 223 // here) 224 if (I != R.end() && std::next(I) == R.end()) 225 return (*I)->getAddrOffsetSectionItem(Index); 226 } 227 if (!AddrOffsetSectionBase) 228 return None; 229 uint64_t Offset = *AddrOffsetSectionBase + Index * getAddressByteSize(); 230 if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize()) 231 return None; 232 DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection, 233 isLittleEndian, getAddressByteSize()); 234 uint64_t Section; 235 uint64_t Address = DA.getRelocatedAddress(&Offset, &Section); 236 return {{Address, Section}}; 237 } 238 239 Optional<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const { 240 if (!StringOffsetsTableContribution) 241 return None; 242 unsigned ItemSize = getDwarfStringOffsetsByteSize(); 243 uint64_t Offset = getStringOffsetsBase() + Index * ItemSize; 244 if (StringOffsetSection.Data.size() < Offset + ItemSize) 245 return None; 246 DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection, 247 isLittleEndian, 0); 248 return DA.getRelocatedValue(ItemSize, &Offset); 249 } 250 251 bool DWARFUnitHeader::extract(DWARFContext &Context, 252 const DWARFDataExtractor &debug_info, 253 uint64_t *offset_ptr, 254 DWARFSectionKind SectionKind, 255 const DWARFUnitIndex *Index, 256 const DWARFUnitIndex::Entry *Entry) { 257 Offset = *offset_ptr; 258 Error Err = Error::success(); 259 IndexEntry = Entry; 260 if (!IndexEntry && Index) 261 IndexEntry = Index->getFromOffset(*offset_ptr); 262 std::tie(Length, FormParams.Format) = 263 debug_info.getInitialLength(offset_ptr, &Err); 264 FormParams.Version = debug_info.getU16(offset_ptr, &Err); 265 if (FormParams.Version >= 5) { 266 UnitType = debug_info.getU8(offset_ptr, &Err); 267 FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err); 268 AbbrOffset = debug_info.getRelocatedValue( 269 FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err); 270 } else { 271 AbbrOffset = debug_info.getRelocatedValue( 272 FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err); 273 FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err); 274 // Fake a unit type based on the section type. This isn't perfect, 275 // but distinguishing compile and type units is generally enough. 276 if (SectionKind == DW_SECT_EXT_TYPES) 277 UnitType = DW_UT_type; 278 else 279 UnitType = DW_UT_compile; 280 } 281 if (isTypeUnit()) { 282 TypeHash = debug_info.getU64(offset_ptr, &Err); 283 TypeOffset = debug_info.getUnsigned( 284 offset_ptr, FormParams.getDwarfOffsetByteSize(), &Err); 285 } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton) 286 DWOId = debug_info.getU64(offset_ptr, &Err); 287 288 if (errorToBool(std::move(Err))) 289 return false; 290 291 if (IndexEntry) { 292 if (AbbrOffset) 293 return false; 294 auto *UnitContrib = IndexEntry->getContribution(); 295 if (!UnitContrib || 296 UnitContrib->Length != (Length + getUnitLengthFieldByteSize())) 297 return false; 298 auto *AbbrEntry = IndexEntry->getContribution(DW_SECT_ABBREV); 299 if (!AbbrEntry) 300 return false; 301 AbbrOffset = AbbrEntry->Offset; 302 } 303 304 // Header fields all parsed, capture the size of this unit header. 305 assert(*offset_ptr - Offset <= 255 && "unexpected header size"); 306 Size = uint8_t(*offset_ptr - Offset); 307 308 // Type offset is unit-relative; should be after the header and before 309 // the end of the current unit. 310 bool TypeOffsetOK = 311 !isTypeUnit() 312 ? true 313 : TypeOffset >= Size && 314 TypeOffset < getLength() + getUnitLengthFieldByteSize(); 315 bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1); 316 bool VersionOK = DWARFContext::isSupportedVersion(getVersion()); 317 bool AddrSizeOK = getAddressByteSize() == 4 || getAddressByteSize() == 8; 318 319 if (!LengthOK || !VersionOK || !AddrSizeOK || !TypeOffsetOK) 320 return false; 321 322 // Keep track of the highest DWARF version we encounter across all units. 323 Context.setMaxVersionIfGreater(getVersion()); 324 return true; 325 } 326 327 // Parse the rangelist table header, including the optional array of offsets 328 // following it (DWARF v5 and later). 329 template<typename ListTableType> 330 static Expected<ListTableType> 331 parseListTableHeader(DWARFDataExtractor &DA, uint64_t Offset, 332 DwarfFormat Format) { 333 // We are expected to be called with Offset 0 or pointing just past the table 334 // header. Correct Offset in the latter case so that it points to the start 335 // of the header. 336 if (Offset > 0) { 337 uint64_t HeaderSize = DWARFListTableHeader::getHeaderSize(Format); 338 if (Offset < HeaderSize) 339 return createStringError(errc::invalid_argument, "did not detect a valid" 340 " list table with base = 0x%" PRIx64 "\n", 341 Offset); 342 Offset -= HeaderSize; 343 } 344 ListTableType Table; 345 if (Error E = Table.extractHeaderAndOffsets(DA, &Offset)) 346 return std::move(E); 347 return Table; 348 } 349 350 Error DWARFUnit::extractRangeList(uint64_t RangeListOffset, 351 DWARFDebugRangeList &RangeList) const { 352 // Require that compile unit is extracted. 353 assert(!DieArray.empty()); 354 DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection, 355 isLittleEndian, getAddressByteSize()); 356 uint64_t ActualRangeListOffset = RangeSectionBase + RangeListOffset; 357 return RangeList.extract(RangesData, &ActualRangeListOffset); 358 } 359 360 void DWARFUnit::clear() { 361 Abbrevs = nullptr; 362 BaseAddr.reset(); 363 RangeSectionBase = 0; 364 LocSectionBase = 0; 365 AddrOffsetSectionBase = None; 366 clearDIEs(false); 367 DWO.reset(); 368 } 369 370 const char *DWARFUnit::getCompilationDir() { 371 return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr); 372 } 373 374 void DWARFUnit::extractDIEsToVector( 375 bool AppendCUDie, bool AppendNonCUDies, 376 std::vector<DWARFDebugInfoEntry> &Dies) const { 377 if (!AppendCUDie && !AppendNonCUDies) 378 return; 379 380 // Set the offset to that of the first DIE and calculate the start of the 381 // next compilation unit header. 382 uint64_t DIEOffset = getOffset() + getHeaderSize(); 383 uint64_t NextCUOffset = getNextUnitOffset(); 384 DWARFDebugInfoEntry DIE; 385 DWARFDataExtractor DebugInfoData = getDebugInfoExtractor(); 386 uint32_t Depth = 0; 387 bool IsCUDie = true; 388 389 while (DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset, 390 Depth)) { 391 if (IsCUDie) { 392 if (AppendCUDie) 393 Dies.push_back(DIE); 394 if (!AppendNonCUDies) 395 break; 396 // The average bytes per DIE entry has been seen to be 397 // around 14-20 so let's pre-reserve the needed memory for 398 // our DIE entries accordingly. 399 Dies.reserve(Dies.size() + getDebugInfoSize() / 14); 400 IsCUDie = false; 401 } else { 402 Dies.push_back(DIE); 403 } 404 405 if (const DWARFAbbreviationDeclaration *AbbrDecl = 406 DIE.getAbbreviationDeclarationPtr()) { 407 // Normal DIE 408 if (AbbrDecl->hasChildren()) 409 ++Depth; 410 } else { 411 // NULL DIE. 412 if (Depth > 0) 413 --Depth; 414 if (Depth == 0) 415 break; // We are done with this compile unit! 416 } 417 } 418 419 // Give a little bit of info if we encounter corrupt DWARF (our offset 420 // should always terminate at or before the start of the next compilation 421 // unit header). 422 if (DIEOffset > NextCUOffset) 423 Context.getWarningHandler()( 424 createStringError(errc::invalid_argument, 425 "DWARF compile unit extends beyond its " 426 "bounds cu 0x%8.8" PRIx64 " " 427 "at 0x%8.8" PRIx64 "\n", 428 getOffset(), DIEOffset)); 429 } 430 431 void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) { 432 if (Error e = tryExtractDIEsIfNeeded(CUDieOnly)) 433 Context.getRecoverableErrorHandler()(std::move(e)); 434 } 435 436 Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) { 437 if ((CUDieOnly && !DieArray.empty()) || 438 DieArray.size() > 1) 439 return Error::success(); // Already parsed. 440 441 bool HasCUDie = !DieArray.empty(); 442 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray); 443 444 if (DieArray.empty()) 445 return Error::success(); 446 447 // If CU DIE was just parsed, copy several attribute values from it. 448 if (HasCUDie) 449 return Error::success(); 450 451 DWARFDie UnitDie(this, &DieArray[0]); 452 if (Optional<uint64_t> DWOId = toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id))) 453 Header.setDWOId(*DWOId); 454 if (!IsDWO) { 455 assert(AddrOffsetSectionBase == None); 456 assert(RangeSectionBase == 0); 457 assert(LocSectionBase == 0); 458 AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_addr_base)); 459 if (!AddrOffsetSectionBase) 460 AddrOffsetSectionBase = 461 toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base)); 462 RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0); 463 LocSectionBase = toSectionOffset(UnitDie.find(DW_AT_loclists_base), 0); 464 } 465 466 // In general, in DWARF v5 and beyond we derive the start of the unit's 467 // contribution to the string offsets table from the unit DIE's 468 // DW_AT_str_offsets_base attribute. Split DWARF units do not use this 469 // attribute, so we assume that there is a contribution to the string 470 // offsets table starting at offset 0 of the debug_str_offsets.dwo section. 471 // In both cases we need to determine the format of the contribution, 472 // which may differ from the unit's format. 473 DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection, 474 isLittleEndian, 0); 475 if (IsDWO || getVersion() >= 5) { 476 auto StringOffsetOrError = 477 IsDWO ? determineStringOffsetsTableContributionDWO(DA) 478 : determineStringOffsetsTableContribution(DA); 479 if (!StringOffsetOrError) 480 return createStringError(errc::invalid_argument, 481 "invalid reference to or invalid content in " 482 ".debug_str_offsets[.dwo]: " + 483 toString(StringOffsetOrError.takeError())); 484 485 StringOffsetsTableContribution = *StringOffsetOrError; 486 } 487 488 // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to 489 // describe address ranges. 490 if (getVersion() >= 5) { 491 // In case of DWP, the base offset from the index has to be added. 492 uint64_t ContributionBaseOffset = 0; 493 if (IsDWO) { 494 if (auto *IndexEntry = Header.getIndexEntry()) 495 if (auto *Contrib = IndexEntry->getContribution(DW_SECT_RNGLISTS)) 496 ContributionBaseOffset = Contrib->Offset; 497 setRangesSection( 498 &Context.getDWARFObj().getRnglistsDWOSection(), 499 ContributionBaseOffset + 500 DWARFListTableHeader::getHeaderSize(Header.getFormat())); 501 } else 502 setRangesSection(&Context.getDWARFObj().getRnglistsSection(), 503 toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0)); 504 if (RangeSection->Data.size()) { 505 // Parse the range list table header. Individual range lists are 506 // extracted lazily. 507 DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection, 508 isLittleEndian, 0); 509 auto TableOrError = parseListTableHeader<DWARFDebugRnglistTable>( 510 RangesDA, RangeSectionBase, Header.getFormat()); 511 if (!TableOrError) 512 return createStringError(errc::invalid_argument, 513 "parsing a range list table: " + 514 toString(TableOrError.takeError())); 515 516 RngListTable = TableOrError.get(); 517 518 // In a split dwarf unit, there is no DW_AT_rnglists_base attribute. 519 // Adjust RangeSectionBase to point past the table header. 520 if (IsDWO && RngListTable) 521 RangeSectionBase = 522 ContributionBaseOffset + RngListTable->getHeaderSize(); 523 } 524 525 // In a split dwarf unit, there is no DW_AT_loclists_base attribute. 526 // Setting LocSectionBase to point past the table header. 527 if (IsDWO) 528 setLocSection(&Context.getDWARFObj().getLoclistsDWOSection(), 529 DWARFListTableHeader::getHeaderSize(Header.getFormat())); 530 else 531 setLocSection(&Context.getDWARFObj().getLoclistsSection(), 532 toSectionOffset(UnitDie.find(DW_AT_loclists_base), 0)); 533 534 if (LocSection->Data.size()) { 535 if (IsDWO) 536 LoclistTableHeader.emplace(".debug_loclists.dwo", "locations"); 537 else 538 LoclistTableHeader.emplace(".debug_loclists", "locations"); 539 540 uint64_t HeaderSize = DWARFListTableHeader::getHeaderSize(Header.getFormat()); 541 uint64_t Offset = getLocSectionBase(); 542 DWARFDataExtractor Data(Context.getDWARFObj(), *LocSection, 543 isLittleEndian, getAddressByteSize()); 544 if (Offset < HeaderSize) 545 return createStringError(errc::invalid_argument, 546 "did not detect a valid" 547 " list table with base = 0x%" PRIx64 "\n", 548 Offset); 549 Offset -= HeaderSize; 550 if (auto *IndexEntry = Header.getIndexEntry()) 551 if (const auto *Contrib = IndexEntry->getContribution(DW_SECT_LOCLISTS)) 552 Offset += Contrib->Offset; 553 if (Error E = LoclistTableHeader->extract(Data, &Offset)) 554 return createStringError(errc::invalid_argument, 555 "parsing a loclist table: " + 556 toString(std::move(E))); 557 } 558 } 559 560 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for 561 // skeleton CU DIE, so that DWARF users not aware of it are not broken. 562 return Error::success(); 563 } 564 565 bool DWARFUnit::parseDWO() { 566 if (IsDWO) 567 return false; 568 if (DWO.get()) 569 return false; 570 DWARFDie UnitDie = getUnitDIE(); 571 if (!UnitDie) 572 return false; 573 auto DWOFileName = getVersion() >= 5 574 ? dwarf::toString(UnitDie.find(DW_AT_dwo_name)) 575 : dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name)); 576 if (!DWOFileName) 577 return false; 578 auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir)); 579 SmallString<16> AbsolutePath; 580 if (sys::path::is_relative(*DWOFileName) && CompilationDir && 581 *CompilationDir) { 582 sys::path::append(AbsolutePath, *CompilationDir); 583 } 584 sys::path::append(AbsolutePath, *DWOFileName); 585 auto DWOId = getDWOId(); 586 if (!DWOId) 587 return false; 588 auto DWOContext = Context.getDWOContext(AbsolutePath); 589 if (!DWOContext) 590 return false; 591 592 DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId); 593 if (!DWOCU) 594 return false; 595 DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU); 596 // Share .debug_addr and .debug_ranges section with compile unit in .dwo 597 if (AddrOffsetSectionBase) 598 DWO->setAddrOffsetSection(AddrOffsetSection, *AddrOffsetSectionBase); 599 if (getVersion() >= 5) { 600 DWO->setRangesSection(&Context.getDWARFObj().getRnglistsDWOSection(), 0); 601 DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection, 602 isLittleEndian, 0); 603 if (auto TableOrError = parseListTableHeader<DWARFDebugRnglistTable>( 604 RangesDA, RangeSectionBase, Header.getFormat())) 605 DWO->RngListTable = TableOrError.get(); 606 else 607 Context.getRecoverableErrorHandler()(createStringError( 608 errc::invalid_argument, "parsing a range list table: %s", 609 toString(TableOrError.takeError()).c_str())); 610 611 if (DWO->RngListTable) 612 DWO->RangeSectionBase = DWO->RngListTable->getHeaderSize(); 613 } else { 614 auto DWORangesBase = UnitDie.getRangesBaseAttribute(); 615 DWO->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0); 616 } 617 618 return true; 619 } 620 621 void DWARFUnit::clearDIEs(bool KeepCUDie) { 622 if (DieArray.size() > (unsigned)KeepCUDie) { 623 DieArray.resize((unsigned)KeepCUDie); 624 DieArray.shrink_to_fit(); 625 } 626 } 627 628 Expected<DWARFAddressRangesVector> 629 DWARFUnit::findRnglistFromOffset(uint64_t Offset) { 630 if (getVersion() <= 4) { 631 DWARFDebugRangeList RangeList; 632 if (Error E = extractRangeList(Offset, RangeList)) 633 return std::move(E); 634 return RangeList.getAbsoluteRanges(getBaseAddress()); 635 } 636 if (RngListTable) { 637 DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection, 638 isLittleEndian, RngListTable->getAddrSize()); 639 auto RangeListOrError = RngListTable->findList(RangesData, Offset); 640 if (RangeListOrError) 641 return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this); 642 return RangeListOrError.takeError(); 643 } 644 645 return createStringError(errc::invalid_argument, 646 "missing or invalid range list table"); 647 } 648 649 Expected<DWARFAddressRangesVector> 650 DWARFUnit::findRnglistFromIndex(uint32_t Index) { 651 if (auto Offset = getRnglistOffset(Index)) 652 return findRnglistFromOffset(*Offset); 653 654 if (RngListTable) 655 return createStringError(errc::invalid_argument, 656 "invalid range list table index %d", Index); 657 658 return createStringError(errc::invalid_argument, 659 "missing or invalid range list table"); 660 } 661 662 Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() { 663 DWARFDie UnitDie = getUnitDIE(); 664 if (!UnitDie) 665 return createStringError(errc::invalid_argument, "No unit DIE"); 666 667 // First, check if unit DIE describes address ranges for the whole unit. 668 auto CUDIERangesOrError = UnitDie.getAddressRanges(); 669 if (!CUDIERangesOrError) 670 return createStringError(errc::invalid_argument, 671 "decoding address ranges: %s", 672 toString(CUDIERangesOrError.takeError()).c_str()); 673 return *CUDIERangesOrError; 674 } 675 676 Expected<DWARFLocationExpressionsVector> 677 DWARFUnit::findLoclistFromOffset(uint64_t Offset) { 678 DWARFLocationExpressionsVector Result; 679 680 Error InterpretationError = Error::success(); 681 682 Error ParseError = getLocationTable().visitAbsoluteLocationList( 683 Offset, getBaseAddress(), 684 [this](uint32_t Index) { return getAddrOffsetSectionItem(Index); }, 685 [&](Expected<DWARFLocationExpression> L) { 686 if (L) 687 Result.push_back(std::move(*L)); 688 else 689 InterpretationError = 690 joinErrors(L.takeError(), std::move(InterpretationError)); 691 return !InterpretationError; 692 }); 693 694 if (ParseError || InterpretationError) 695 return joinErrors(std::move(ParseError), std::move(InterpretationError)); 696 697 return Result; 698 } 699 700 void DWARFUnit::updateAddressDieMap(DWARFDie Die) { 701 if (Die.isSubroutineDIE()) { 702 auto DIERangesOrError = Die.getAddressRanges(); 703 if (DIERangesOrError) { 704 for (const auto &R : DIERangesOrError.get()) { 705 // Ignore 0-sized ranges. 706 if (R.LowPC == R.HighPC) 707 continue; 708 auto B = AddrDieMap.upper_bound(R.LowPC); 709 if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) { 710 // The range is a sub-range of existing ranges, we need to split the 711 // existing range. 712 if (R.HighPC < B->second.first) 713 AddrDieMap[R.HighPC] = B->second; 714 if (R.LowPC > B->first) 715 AddrDieMap[B->first].first = R.LowPC; 716 } 717 AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die); 718 } 719 } else 720 llvm::consumeError(DIERangesOrError.takeError()); 721 } 722 // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to 723 // simplify the logic to update AddrDieMap. The child's range will always 724 // be equal or smaller than the parent's range. With this assumption, when 725 // adding one range into the map, it will at most split a range into 3 726 // sub-ranges. 727 for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling()) 728 updateAddressDieMap(Child); 729 } 730 731 DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) { 732 extractDIEsIfNeeded(false); 733 if (AddrDieMap.empty()) 734 updateAddressDieMap(getUnitDIE()); 735 auto R = AddrDieMap.upper_bound(Address); 736 if (R == AddrDieMap.begin()) 737 return DWARFDie(); 738 // upper_bound's previous item contains Address. 739 --R; 740 if (Address >= R->second.first) 741 return DWARFDie(); 742 return R->second.second; 743 } 744 745 void 746 DWARFUnit::getInlinedChainForAddress(uint64_t Address, 747 SmallVectorImpl<DWARFDie> &InlinedChain) { 748 assert(InlinedChain.empty()); 749 // Try to look for subprogram DIEs in the DWO file. 750 parseDWO(); 751 // First, find the subroutine that contains the given address (the leaf 752 // of inlined chain). 753 DWARFDie SubroutineDIE = 754 (DWO ? *DWO : *this).getSubroutineForAddress(Address); 755 756 if (!SubroutineDIE) 757 return; 758 759 while (!SubroutineDIE.isSubprogramDIE()) { 760 if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine) 761 InlinedChain.push_back(SubroutineDIE); 762 SubroutineDIE = SubroutineDIE.getParent(); 763 } 764 InlinedChain.push_back(SubroutineDIE); 765 } 766 767 const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context, 768 DWARFSectionKind Kind) { 769 if (Kind == DW_SECT_INFO) 770 return Context.getCUIndex(); 771 assert(Kind == DW_SECT_EXT_TYPES); 772 return Context.getTUIndex(); 773 } 774 775 DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) { 776 if (!Die) 777 return DWARFDie(); 778 const uint32_t Depth = Die->getDepth(); 779 // Unit DIEs always have a depth of zero and never have parents. 780 if (Depth == 0) 781 return DWARFDie(); 782 // Depth of 1 always means parent is the compile/type unit. 783 if (Depth == 1) 784 return getUnitDIE(); 785 // Look for previous DIE with a depth that is one less than the Die's depth. 786 const uint32_t ParentDepth = Depth - 1; 787 for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) { 788 if (DieArray[I].getDepth() == ParentDepth) 789 return DWARFDie(this, &DieArray[I]); 790 } 791 return DWARFDie(); 792 } 793 794 DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) { 795 if (!Die) 796 return DWARFDie(); 797 uint32_t Depth = Die->getDepth(); 798 // Unit DIEs always have a depth of zero and never have siblings. 799 if (Depth == 0) 800 return DWARFDie(); 801 // NULL DIEs don't have siblings. 802 if (Die->getAbbreviationDeclarationPtr() == nullptr) 803 return DWARFDie(); 804 805 // Find the next DIE whose depth is the same as the Die's depth. 806 for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx; 807 ++I) { 808 if (DieArray[I].getDepth() == Depth) 809 return DWARFDie(this, &DieArray[I]); 810 } 811 return DWARFDie(); 812 } 813 814 DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) { 815 if (!Die) 816 return DWARFDie(); 817 uint32_t Depth = Die->getDepth(); 818 // Unit DIEs always have a depth of zero and never have siblings. 819 if (Depth == 0) 820 return DWARFDie(); 821 822 // Find the previous DIE whose depth is the same as the Die's depth. 823 for (size_t I = getDIEIndex(Die); I > 0;) { 824 --I; 825 if (DieArray[I].getDepth() == Depth - 1) 826 return DWARFDie(); 827 if (DieArray[I].getDepth() == Depth) 828 return DWARFDie(this, &DieArray[I]); 829 } 830 return DWARFDie(); 831 } 832 833 DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) { 834 if (!Die->hasChildren()) 835 return DWARFDie(); 836 837 // We do not want access out of bounds when parsing corrupted debug data. 838 size_t I = getDIEIndex(Die) + 1; 839 if (I >= DieArray.size()) 840 return DWARFDie(); 841 return DWARFDie(this, &DieArray[I]); 842 } 843 844 DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) { 845 if (!Die->hasChildren()) 846 return DWARFDie(); 847 848 uint32_t Depth = Die->getDepth(); 849 for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx; 850 ++I) { 851 if (DieArray[I].getDepth() == Depth + 1 && 852 DieArray[I].getTag() == dwarf::DW_TAG_null) 853 return DWARFDie(this, &DieArray[I]); 854 assert(DieArray[I].getDepth() > Depth && "Not processing children?"); 855 } 856 return DWARFDie(); 857 } 858 859 const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const { 860 if (!Abbrevs) 861 Abbrevs = Abbrev->getAbbreviationDeclarationSet(Header.getAbbrOffset()); 862 return Abbrevs; 863 } 864 865 llvm::Optional<object::SectionedAddress> DWARFUnit::getBaseAddress() { 866 if (BaseAddr) 867 return BaseAddr; 868 869 DWARFDie UnitDie = getUnitDIE(); 870 Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc}); 871 BaseAddr = toSectionedAddress(PC); 872 return BaseAddr; 873 } 874 875 Expected<StrOffsetsContributionDescriptor> 876 StrOffsetsContributionDescriptor::validateContributionSize( 877 DWARFDataExtractor &DA) { 878 uint8_t EntrySize = getDwarfOffsetByteSize(); 879 // In order to ensure that we don't read a partial record at the end of 880 // the section we validate for a multiple of the entry size. 881 uint64_t ValidationSize = alignTo(Size, EntrySize); 882 // Guard against overflow. 883 if (ValidationSize >= Size) 884 if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize)) 885 return *this; 886 return createStringError(errc::invalid_argument, "length exceeds section size"); 887 } 888 889 // Look for a DWARF64-formatted contribution to the string offsets table 890 // starting at a given offset and record it in a descriptor. 891 static Expected<StrOffsetsContributionDescriptor> 892 parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) { 893 if (!DA.isValidOffsetForDataOfSize(Offset, 16)) 894 return createStringError(errc::invalid_argument, "section offset exceeds section size"); 895 896 if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64) 897 return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit"); 898 899 uint64_t Size = DA.getU64(&Offset); 900 uint8_t Version = DA.getU16(&Offset); 901 (void)DA.getU16(&Offset); // padding 902 // The encoded length includes the 2-byte version field and the 2-byte 903 // padding, so we need to subtract them out when we populate the descriptor. 904 return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64); 905 } 906 907 // Look for a DWARF32-formatted contribution to the string offsets table 908 // starting at a given offset and record it in a descriptor. 909 static Expected<StrOffsetsContributionDescriptor> 910 parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) { 911 if (!DA.isValidOffsetForDataOfSize(Offset, 8)) 912 return createStringError(errc::invalid_argument, "section offset exceeds section size"); 913 914 uint32_t ContributionSize = DA.getU32(&Offset); 915 if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved) 916 return createStringError(errc::invalid_argument, "invalid length"); 917 918 uint8_t Version = DA.getU16(&Offset); 919 (void)DA.getU16(&Offset); // padding 920 // The encoded length includes the 2-byte version field and the 2-byte 921 // padding, so we need to subtract them out when we populate the descriptor. 922 return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version, 923 DWARF32); 924 } 925 926 static Expected<StrOffsetsContributionDescriptor> 927 parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA, 928 llvm::dwarf::DwarfFormat Format, 929 uint64_t Offset) { 930 StrOffsetsContributionDescriptor Desc; 931 switch (Format) { 932 case dwarf::DwarfFormat::DWARF64: { 933 if (Offset < 16) 934 return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix"); 935 auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16); 936 if (!DescOrError) 937 return DescOrError.takeError(); 938 Desc = *DescOrError; 939 break; 940 } 941 case dwarf::DwarfFormat::DWARF32: { 942 if (Offset < 8) 943 return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix"); 944 auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8); 945 if (!DescOrError) 946 return DescOrError.takeError(); 947 Desc = *DescOrError; 948 break; 949 } 950 } 951 return Desc.validateContributionSize(DA); 952 } 953 954 Expected<Optional<StrOffsetsContributionDescriptor>> 955 DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) { 956 uint64_t Offset; 957 if (IsDWO) { 958 Offset = 0; 959 if (DA.getData().data() == nullptr) 960 return None; 961 } else { 962 auto OptOffset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base)); 963 if (!OptOffset) 964 return None; 965 Offset = *OptOffset; 966 } 967 auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset); 968 if (!DescOrError) 969 return DescOrError.takeError(); 970 return *DescOrError; 971 } 972 973 Expected<Optional<StrOffsetsContributionDescriptor>> 974 DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor & DA) { 975 uint64_t Offset = 0; 976 auto IndexEntry = Header.getIndexEntry(); 977 const auto *C = 978 IndexEntry ? IndexEntry->getContribution(DW_SECT_STR_OFFSETS) : nullptr; 979 if (C) 980 Offset = C->Offset; 981 if (getVersion() >= 5) { 982 if (DA.getData().data() == nullptr) 983 return None; 984 Offset += Header.getFormat() == dwarf::DwarfFormat::DWARF32 ? 8 : 16; 985 // Look for a valid contribution at the given offset. 986 auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset); 987 if (!DescOrError) 988 return DescOrError.takeError(); 989 return *DescOrError; 990 } 991 // Prior to DWARF v5, we derive the contribution size from the 992 // index table (in a package file). In a .dwo file it is simply 993 // the length of the string offsets section. 994 if (!IndexEntry) 995 return { 996 Optional<StrOffsetsContributionDescriptor>( 997 {0, StringOffsetSection.Data.size(), 4, DWARF32})}; 998 if (C) 999 return {Optional<StrOffsetsContributionDescriptor>( 1000 {C->Offset, C->Length, 4, DWARF32})}; 1001 return None; 1002 } 1003