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