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