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