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