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