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 (Error SizeErr = DWARFContext::checkAddressSizeSupported( 319 getAddressByteSize(), errc::invalid_argument, 320 "DWARF unit at offset 0x%8.8" PRIx64, Offset)) { 321 Context.getWarningHandler()(std::move(SizeErr)); 322 return false; 323 } 324 325 // Keep track of the highest DWARF version we encounter across all units. 326 Context.setMaxVersionIfGreater(getVersion()); 327 return true; 328 } 329 330 bool DWARFUnitHeader::applyIndexEntry(const DWARFUnitIndex::Entry *Entry) { 331 assert(Entry); 332 assert(!IndexEntry); 333 IndexEntry = Entry; 334 if (AbbrOffset) 335 return false; 336 auto *UnitContrib = IndexEntry->getContribution(); 337 if (!UnitContrib || 338 UnitContrib->Length != (getLength() + getUnitLengthFieldByteSize())) 339 return false; 340 auto *AbbrEntry = IndexEntry->getContribution(DW_SECT_ABBREV); 341 if (!AbbrEntry) 342 return false; 343 AbbrOffset = AbbrEntry->Offset; 344 return true; 345 } 346 347 Error DWARFUnit::extractRangeList(uint64_t RangeListOffset, 348 DWARFDebugRangeList &RangeList) const { 349 // Require that compile unit is extracted. 350 assert(!DieArray.empty()); 351 DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection, 352 isLittleEndian, getAddressByteSize()); 353 uint64_t ActualRangeListOffset = RangeSectionBase + RangeListOffset; 354 return RangeList.extract(RangesData, &ActualRangeListOffset); 355 } 356 357 void DWARFUnit::clear() { 358 Abbrevs = nullptr; 359 BaseAddr.reset(); 360 RangeSectionBase = 0; 361 LocSectionBase = 0; 362 AddrOffsetSectionBase = None; 363 SU = nullptr; 364 clearDIEs(false); 365 DWO.reset(); 366 } 367 368 const char *DWARFUnit::getCompilationDir() { 369 return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr); 370 } 371 372 void DWARFUnit::extractDIEsToVector( 373 bool AppendCUDie, bool AppendNonCUDies, 374 std::vector<DWARFDebugInfoEntry> &Dies) const { 375 if (!AppendCUDie && !AppendNonCUDies) 376 return; 377 378 // Set the offset to that of the first DIE and calculate the start of the 379 // next compilation unit header. 380 uint64_t DIEOffset = getOffset() + getHeaderSize(); 381 uint64_t NextCUOffset = getNextUnitOffset(); 382 DWARFDebugInfoEntry DIE; 383 DWARFDataExtractor DebugInfoData = getDebugInfoExtractor(); 384 // The end offset has been already checked by DWARFUnitHeader::extract. 385 assert(DebugInfoData.isValidOffset(NextCUOffset - 1)); 386 std::vector<uint32_t> Parents; 387 std::vector<uint32_t> PrevSiblings; 388 bool IsCUDie = true; 389 390 assert( 391 ((AppendCUDie && Dies.empty()) || (!AppendCUDie && Dies.size() == 1)) && 392 "Dies array is not empty"); 393 394 // Fill Parents and Siblings stacks with initial value. 395 Parents.push_back(UINT32_MAX); 396 if (!AppendCUDie) 397 Parents.push_back(0); 398 PrevSiblings.push_back(0); 399 400 // Start to extract dies. 401 do { 402 assert(Parents.size() > 0 && "Empty parents stack"); 403 assert((Parents.back() == UINT32_MAX || Parents.back() <= Dies.size()) && 404 "Wrong parent index"); 405 406 // Extract die. Stop if any error occured. 407 if (!DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset, 408 Parents.back())) 409 break; 410 411 // If previous sibling is remembered then update it`s SiblingIdx field. 412 if (PrevSiblings.back() > 0) { 413 assert(PrevSiblings.back() < Dies.size() && 414 "Previous sibling index is out of Dies boundaries"); 415 Dies[PrevSiblings.back()].setSiblingIdx(Dies.size()); 416 } 417 418 // Store die into the Dies vector. 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 } else { 429 // Remember last previous sibling. 430 PrevSiblings.back() = Dies.size(); 431 432 Dies.push_back(DIE); 433 } 434 435 // Check for new children scope. 436 if (const DWARFAbbreviationDeclaration *AbbrDecl = 437 DIE.getAbbreviationDeclarationPtr()) { 438 if (AbbrDecl->hasChildren()) { 439 if (AppendCUDie || !IsCUDie) { 440 assert(Dies.size() > 0 && "Dies does not contain any die"); 441 Parents.push_back(Dies.size() - 1); 442 PrevSiblings.push_back(0); 443 } 444 } else if (IsCUDie) 445 // Stop if we have single compile unit die w/o children. 446 break; 447 } else { 448 // NULL DIE: finishes current children scope. 449 Parents.pop_back(); 450 PrevSiblings.pop_back(); 451 } 452 453 if (IsCUDie) 454 IsCUDie = false; 455 456 // Stop when compile unit die is removed from the parents stack. 457 } while (Parents.size() > 1); 458 } 459 460 void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) { 461 if (Error e = tryExtractDIEsIfNeeded(CUDieOnly)) 462 Context.getRecoverableErrorHandler()(std::move(e)); 463 } 464 465 Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) { 466 if ((CUDieOnly && !DieArray.empty()) || 467 DieArray.size() > 1) 468 return Error::success(); // Already parsed. 469 470 bool HasCUDie = !DieArray.empty(); 471 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray); 472 473 if (DieArray.empty()) 474 return Error::success(); 475 476 // If CU DIE was just parsed, copy several attribute values from it. 477 if (HasCUDie) 478 return Error::success(); 479 480 DWARFDie UnitDie(this, &DieArray[0]); 481 if (Optional<uint64_t> DWOId = toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id))) 482 Header.setDWOId(*DWOId); 483 if (!IsDWO) { 484 assert(AddrOffsetSectionBase == None); 485 assert(RangeSectionBase == 0); 486 assert(LocSectionBase == 0); 487 AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_addr_base)); 488 if (!AddrOffsetSectionBase) 489 AddrOffsetSectionBase = 490 toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base)); 491 RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0); 492 LocSectionBase = toSectionOffset(UnitDie.find(DW_AT_loclists_base), 0); 493 } 494 495 // In general, in DWARF v5 and beyond we derive the start of the unit's 496 // contribution to the string offsets table from the unit DIE's 497 // DW_AT_str_offsets_base attribute. Split DWARF units do not use this 498 // attribute, so we assume that there is a contribution to the string 499 // offsets table starting at offset 0 of the debug_str_offsets.dwo section. 500 // In both cases we need to determine the format of the contribution, 501 // which may differ from the unit's format. 502 DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection, 503 isLittleEndian, 0); 504 if (IsDWO || getVersion() >= 5) { 505 auto StringOffsetOrError = 506 IsDWO ? determineStringOffsetsTableContributionDWO(DA) 507 : determineStringOffsetsTableContribution(DA); 508 if (!StringOffsetOrError) 509 return createStringError(errc::invalid_argument, 510 "invalid reference to or invalid content in " 511 ".debug_str_offsets[.dwo]: " + 512 toString(StringOffsetOrError.takeError())); 513 514 StringOffsetsTableContribution = *StringOffsetOrError; 515 } 516 517 // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to 518 // describe address ranges. 519 if (getVersion() >= 5) { 520 // In case of DWP, the base offset from the index has to be added. 521 if (IsDWO) { 522 uint64_t ContributionBaseOffset = 0; 523 if (auto *IndexEntry = Header.getIndexEntry()) 524 if (auto *Contrib = IndexEntry->getContribution(DW_SECT_RNGLISTS)) 525 ContributionBaseOffset = Contrib->Offset; 526 setRangesSection( 527 &Context.getDWARFObj().getRnglistsDWOSection(), 528 ContributionBaseOffset + 529 DWARFListTableHeader::getHeaderSize(Header.getFormat())); 530 } else 531 setRangesSection(&Context.getDWARFObj().getRnglistsSection(), 532 toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 533 DWARFListTableHeader::getHeaderSize( 534 Header.getFormat()))); 535 } 536 537 if (IsDWO) { 538 // If we are reading a package file, we need to adjust the location list 539 // data based on the index entries. 540 StringRef Data = Header.getVersion() >= 5 541 ? Context.getDWARFObj().getLoclistsDWOSection().Data 542 : Context.getDWARFObj().getLocDWOSection().Data; 543 if (auto *IndexEntry = Header.getIndexEntry()) 544 if (const auto *C = IndexEntry->getContribution( 545 Header.getVersion() >= 5 ? DW_SECT_LOCLISTS : DW_SECT_EXT_LOC)) 546 Data = Data.substr(C->Offset, C->Length); 547 548 DWARFDataExtractor DWARFData(Data, isLittleEndian, getAddressByteSize()); 549 LocTable = 550 std::make_unique<DWARFDebugLoclists>(DWARFData, Header.getVersion()); 551 LocSectionBase = DWARFListTableHeader::getHeaderSize(Header.getFormat()); 552 } else if (getVersion() >= 5) { 553 LocTable = std::make_unique<DWARFDebugLoclists>( 554 DWARFDataExtractor(Context.getDWARFObj(), 555 Context.getDWARFObj().getLoclistsSection(), 556 isLittleEndian, getAddressByteSize()), 557 getVersion()); 558 } else { 559 LocTable = std::make_unique<DWARFDebugLoc>(DWARFDataExtractor( 560 Context.getDWARFObj(), Context.getDWARFObj().getLocSection(), 561 isLittleEndian, getAddressByteSize())); 562 } 563 564 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for 565 // skeleton CU DIE, so that DWARF users not aware of it are not broken. 566 return Error::success(); 567 } 568 569 bool DWARFUnit::parseDWO() { 570 if (IsDWO) 571 return false; 572 if (DWO.get()) 573 return false; 574 DWARFDie UnitDie = getUnitDIE(); 575 if (!UnitDie) 576 return false; 577 auto DWOFileName = getVersion() >= 5 578 ? dwarf::toString(UnitDie.find(DW_AT_dwo_name)) 579 : dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name)); 580 if (!DWOFileName) 581 return false; 582 auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir)); 583 SmallString<16> AbsolutePath; 584 if (sys::path::is_relative(*DWOFileName) && CompilationDir && 585 *CompilationDir) { 586 sys::path::append(AbsolutePath, *CompilationDir); 587 } 588 sys::path::append(AbsolutePath, *DWOFileName); 589 auto DWOId = getDWOId(); 590 if (!DWOId) 591 return false; 592 auto DWOContext = Context.getDWOContext(AbsolutePath); 593 if (!DWOContext) 594 return false; 595 596 DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId); 597 if (!DWOCU) 598 return false; 599 DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU); 600 DWO->setSkeletonUnit(this); 601 // Share .debug_addr and .debug_ranges section with compile unit in .dwo 602 if (AddrOffsetSectionBase) 603 DWO->setAddrOffsetSection(AddrOffsetSection, *AddrOffsetSectionBase); 604 if (getVersion() == 4) { 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 // Do not use resize() + shrink_to_fit() to free memory occupied by dies. 614 // shrink_to_fit() is a *non-binding* request to reduce capacity() to size(). 615 // It depends on the implementation whether the request is fulfilled. 616 // Create a new vector with a small capacity and assign it to the DieArray to 617 // have previous contents freed. 618 DieArray = (KeepCUDie && !DieArray.empty()) 619 ? std::vector<DWARFDebugInfoEntry>({DieArray[0]}) 620 : std::vector<DWARFDebugInfoEntry>(); 621 } 622 623 Expected<DWARFAddressRangesVector> 624 DWARFUnit::findRnglistFromOffset(uint64_t Offset) { 625 if (getVersion() <= 4) { 626 DWARFDebugRangeList RangeList; 627 if (Error E = extractRangeList(Offset, RangeList)) 628 return std::move(E); 629 return RangeList.getAbsoluteRanges(getBaseAddress()); 630 } 631 DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection, 632 isLittleEndian, Header.getAddressByteSize()); 633 DWARFDebugRnglistTable RnglistTable; 634 auto RangeListOrError = RnglistTable.findList(RangesData, Offset); 635 if (RangeListOrError) 636 return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this); 637 return RangeListOrError.takeError(); 638 } 639 640 Expected<DWARFAddressRangesVector> 641 DWARFUnit::findRnglistFromIndex(uint32_t Index) { 642 if (auto Offset = getRnglistOffset(Index)) 643 return findRnglistFromOffset(*Offset); 644 645 return createStringError(errc::invalid_argument, 646 "invalid range list table index %d (possibly " 647 "missing the entire range list table)", 648 Index); 649 } 650 651 Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() { 652 DWARFDie UnitDie = getUnitDIE(); 653 if (!UnitDie) 654 return createStringError(errc::invalid_argument, "No unit DIE"); 655 656 // First, check if unit DIE describes address ranges for the whole unit. 657 auto CUDIERangesOrError = UnitDie.getAddressRanges(); 658 if (!CUDIERangesOrError) 659 return createStringError(errc::invalid_argument, 660 "decoding address ranges: %s", 661 toString(CUDIERangesOrError.takeError()).c_str()); 662 return *CUDIERangesOrError; 663 } 664 665 Expected<DWARFLocationExpressionsVector> 666 DWARFUnit::findLoclistFromOffset(uint64_t Offset) { 667 DWARFLocationExpressionsVector Result; 668 669 Error InterpretationError = Error::success(); 670 671 Error ParseError = getLocationTable().visitAbsoluteLocationList( 672 Offset, getBaseAddress(), 673 [this](uint32_t Index) { return getAddrOffsetSectionItem(Index); }, 674 [&](Expected<DWARFLocationExpression> L) { 675 if (L) 676 Result.push_back(std::move(*L)); 677 else 678 InterpretationError = 679 joinErrors(L.takeError(), std::move(InterpretationError)); 680 return !InterpretationError; 681 }); 682 683 if (ParseError || InterpretationError) 684 return joinErrors(std::move(ParseError), std::move(InterpretationError)); 685 686 return Result; 687 } 688 689 void DWARFUnit::updateAddressDieMap(DWARFDie Die) { 690 if (Die.isSubroutineDIE()) { 691 auto DIERangesOrError = Die.getAddressRanges(); 692 if (DIERangesOrError) { 693 for (const auto &R : DIERangesOrError.get()) { 694 // Ignore 0-sized ranges. 695 if (R.LowPC == R.HighPC) 696 continue; 697 auto B = AddrDieMap.upper_bound(R.LowPC); 698 if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) { 699 // The range is a sub-range of existing ranges, we need to split the 700 // existing range. 701 if (R.HighPC < B->second.first) 702 AddrDieMap[R.HighPC] = B->second; 703 if (R.LowPC > B->first) 704 AddrDieMap[B->first].first = R.LowPC; 705 } 706 AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die); 707 } 708 } else 709 llvm::consumeError(DIERangesOrError.takeError()); 710 } 711 // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to 712 // simplify the logic to update AddrDieMap. The child's range will always 713 // be equal or smaller than the parent's range. With this assumption, when 714 // adding one range into the map, it will at most split a range into 3 715 // sub-ranges. 716 for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling()) 717 updateAddressDieMap(Child); 718 } 719 720 DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) { 721 extractDIEsIfNeeded(false); 722 if (AddrDieMap.empty()) 723 updateAddressDieMap(getUnitDIE()); 724 auto R = AddrDieMap.upper_bound(Address); 725 if (R == AddrDieMap.begin()) 726 return DWARFDie(); 727 // upper_bound's previous item contains Address. 728 --R; 729 if (Address >= R->second.first) 730 return DWARFDie(); 731 return R->second.second; 732 } 733 734 void 735 DWARFUnit::getInlinedChainForAddress(uint64_t Address, 736 SmallVectorImpl<DWARFDie> &InlinedChain) { 737 assert(InlinedChain.empty()); 738 // Try to look for subprogram DIEs in the DWO file. 739 parseDWO(); 740 // First, find the subroutine that contains the given address (the leaf 741 // of inlined chain). 742 DWARFDie SubroutineDIE = 743 (DWO ? *DWO : *this).getSubroutineForAddress(Address); 744 745 while (SubroutineDIE) { 746 if (SubroutineDIE.isSubprogramDIE()) { 747 InlinedChain.push_back(SubroutineDIE); 748 return; 749 } 750 if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine) 751 InlinedChain.push_back(SubroutineDIE); 752 SubroutineDIE = SubroutineDIE.getParent(); 753 } 754 } 755 756 const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context, 757 DWARFSectionKind Kind) { 758 if (Kind == DW_SECT_INFO) 759 return Context.getCUIndex(); 760 assert(Kind == DW_SECT_EXT_TYPES); 761 return Context.getTUIndex(); 762 } 763 764 DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) { 765 if (!Die) 766 return DWARFDie(); 767 768 if (Optional<uint32_t> ParentIdx = Die->getParentIdx()) { 769 assert(*ParentIdx < DieArray.size() && 770 "ParentIdx is out of DieArray boundaries"); 771 return DWARFDie(this, &DieArray[*ParentIdx]); 772 } 773 774 return DWARFDie(); 775 } 776 777 DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) { 778 if (!Die) 779 return DWARFDie(); 780 781 if (Optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) { 782 assert(*SiblingIdx < DieArray.size() && 783 "SiblingIdx is out of DieArray boundaries"); 784 return DWARFDie(this, &DieArray[*SiblingIdx]); 785 } 786 787 return DWARFDie(); 788 } 789 790 DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) { 791 if (!Die) 792 return DWARFDie(); 793 794 Optional<uint32_t> ParentIdx = Die->getParentIdx(); 795 if (!ParentIdx) 796 // Die is a root die, there is no previous sibling. 797 return DWARFDie(); 798 799 assert(*ParentIdx < DieArray.size() && 800 "ParentIdx is out of DieArray boundaries"); 801 assert(getDIEIndex(Die) > 0 && "Die is a root die"); 802 803 uint32_t PrevDieIdx = getDIEIndex(Die) - 1; 804 if (PrevDieIdx == *ParentIdx) 805 // Immediately previous node is parent, there is no previous sibling. 806 return DWARFDie(); 807 808 while (DieArray[PrevDieIdx].getParentIdx() != *ParentIdx) { 809 PrevDieIdx = *DieArray[PrevDieIdx].getParentIdx(); 810 811 assert(PrevDieIdx < DieArray.size() && 812 "PrevDieIdx is out of DieArray boundaries"); 813 assert(PrevDieIdx >= *ParentIdx && 814 "PrevDieIdx is not a child of parent of Die"); 815 } 816 817 return DWARFDie(this, &DieArray[PrevDieIdx]); 818 } 819 820 DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) { 821 if (!Die->hasChildren()) 822 return DWARFDie(); 823 824 // TODO: Instead of checking here for invalid die we might reject 825 // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector). 826 // We do not want access out of bounds when parsing corrupted debug data. 827 size_t I = getDIEIndex(Die) + 1; 828 if (I >= DieArray.size()) 829 return DWARFDie(); 830 return DWARFDie(this, &DieArray[I]); 831 } 832 833 DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) { 834 if (!Die->hasChildren()) 835 return DWARFDie(); 836 837 if (Optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) { 838 assert(*SiblingIdx < DieArray.size() && 839 "SiblingIdx is out of DieArray boundaries"); 840 assert(DieArray[*SiblingIdx - 1].getTag() == dwarf::DW_TAG_null && 841 "Bad end of children marker"); 842 return DWARFDie(this, &DieArray[*SiblingIdx - 1]); 843 } 844 845 // If SiblingIdx is set for non-root dies we could be sure that DWARF is 846 // correct and "end of children marker" must be found. For root die we do not 847 // have such a guarantee(parsing root die might be stopped if "end of children 848 // marker" is missing, SiblingIdx is always zero for root die). That is why we 849 // do not use assertion for checking for "end of children marker" for root 850 // die. 851 852 // TODO: Instead of checking here for invalid die we might reject 853 // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector). 854 if (getDIEIndex(Die) == 0 && DieArray.size() > 1 && 855 DieArray.back().getTag() == dwarf::DW_TAG_null) { 856 // For the unit die we might take last item from DieArray. 857 assert(getDIEIndex(Die) == getDIEIndex(getUnitDIE()) && "Bad unit die"); 858 return DWARFDie(this, &DieArray.back()); 859 } 860 861 return DWARFDie(); 862 } 863 864 const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const { 865 if (!Abbrevs) 866 Abbrevs = Abbrev->getAbbreviationDeclarationSet(getAbbreviationsOffset()); 867 return Abbrevs; 868 } 869 870 llvm::Optional<object::SectionedAddress> DWARFUnit::getBaseAddress() { 871 if (BaseAddr) 872 return BaseAddr; 873 874 DWARFDie UnitDie = getUnitDIE(); 875 Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc}); 876 BaseAddr = toSectionedAddress(PC); 877 return BaseAddr; 878 } 879 880 Expected<StrOffsetsContributionDescriptor> 881 StrOffsetsContributionDescriptor::validateContributionSize( 882 DWARFDataExtractor &DA) { 883 uint8_t EntrySize = getDwarfOffsetByteSize(); 884 // In order to ensure that we don't read a partial record at the end of 885 // the section we validate for a multiple of the entry size. 886 uint64_t ValidationSize = alignTo(Size, EntrySize); 887 // Guard against overflow. 888 if (ValidationSize >= Size) 889 if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize)) 890 return *this; 891 return createStringError(errc::invalid_argument, "length exceeds section size"); 892 } 893 894 // Look for a DWARF64-formatted contribution to the string offsets table 895 // starting at a given offset and record it in a descriptor. 896 static Expected<StrOffsetsContributionDescriptor> 897 parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) { 898 if (!DA.isValidOffsetForDataOfSize(Offset, 16)) 899 return createStringError(errc::invalid_argument, "section offset exceeds section size"); 900 901 if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64) 902 return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit"); 903 904 uint64_t Size = DA.getU64(&Offset); 905 uint8_t Version = DA.getU16(&Offset); 906 (void)DA.getU16(&Offset); // padding 907 // The encoded length includes the 2-byte version field and the 2-byte 908 // padding, so we need to subtract them out when we populate the descriptor. 909 return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64); 910 } 911 912 // Look for a DWARF32-formatted contribution to the string offsets table 913 // starting at a given offset and record it in a descriptor. 914 static Expected<StrOffsetsContributionDescriptor> 915 parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) { 916 if (!DA.isValidOffsetForDataOfSize(Offset, 8)) 917 return createStringError(errc::invalid_argument, "section offset exceeds section size"); 918 919 uint32_t ContributionSize = DA.getU32(&Offset); 920 if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved) 921 return createStringError(errc::invalid_argument, "invalid length"); 922 923 uint8_t Version = DA.getU16(&Offset); 924 (void)DA.getU16(&Offset); // padding 925 // The encoded length includes the 2-byte version field and the 2-byte 926 // padding, so we need to subtract them out when we populate the descriptor. 927 return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version, 928 DWARF32); 929 } 930 931 static Expected<StrOffsetsContributionDescriptor> 932 parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA, 933 llvm::dwarf::DwarfFormat Format, 934 uint64_t Offset) { 935 StrOffsetsContributionDescriptor Desc; 936 switch (Format) { 937 case dwarf::DwarfFormat::DWARF64: { 938 if (Offset < 16) 939 return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix"); 940 auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16); 941 if (!DescOrError) 942 return DescOrError.takeError(); 943 Desc = *DescOrError; 944 break; 945 } 946 case dwarf::DwarfFormat::DWARF32: { 947 if (Offset < 8) 948 return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix"); 949 auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8); 950 if (!DescOrError) 951 return DescOrError.takeError(); 952 Desc = *DescOrError; 953 break; 954 } 955 } 956 return Desc.validateContributionSize(DA); 957 } 958 959 Expected<Optional<StrOffsetsContributionDescriptor>> 960 DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) { 961 assert(!IsDWO); 962 auto OptOffset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base)); 963 if (!OptOffset) 964 return None; 965 auto DescOrError = 966 parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), *OptOffset); 967 if (!DescOrError) 968 return DescOrError.takeError(); 969 return *DescOrError; 970 } 971 972 Expected<Optional<StrOffsetsContributionDescriptor>> 973 DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor & DA) { 974 assert(IsDWO); 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 StrOffsetsContributionDescriptor Desc; 995 if (C) 996 Desc = StrOffsetsContributionDescriptor(C->Offset, C->Length, 4, 997 Header.getFormat()); 998 else if (!IndexEntry && !StringOffsetSection.Data.empty()) 999 Desc = StrOffsetsContributionDescriptor(0, StringOffsetSection.Data.size(), 1000 4, Header.getFormat()); 1001 else 1002 return None; 1003 auto DescOrError = Desc.validateContributionSize(DA); 1004 if (!DescOrError) 1005 return DescOrError.takeError(); 1006 return *DescOrError; 1007 } 1008 1009 Optional<uint64_t> DWARFUnit::getRnglistOffset(uint32_t Index) { 1010 DataExtractor RangesData(RangeSection->Data, isLittleEndian, 1011 getAddressByteSize()); 1012 DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection, 1013 isLittleEndian, 0); 1014 if (Optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry( 1015 RangesData, RangeSectionBase, getFormat(), Index)) 1016 return *Off + RangeSectionBase; 1017 return None; 1018 } 1019 1020 Optional<uint64_t> DWARFUnit::getLoclistOffset(uint32_t Index) { 1021 if (Optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry( 1022 LocTable->getData(), LocSectionBase, getFormat(), Index)) 1023 return *Off + LocSectionBase; 1024 return None; 1025 } 1026