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