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/ADT/SmallString.h" 11 #include "llvm/ADT/STLExtras.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/DWARFDie.h" 18 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" 19 #include "llvm/DebugInfo/DWARF/DWARFUnit.h" 20 #include "llvm/Object/ObjectFile.h" 21 #include "llvm/Support/Casting.h" 22 #include "llvm/Support/DataExtractor.h" 23 #include "llvm/Support/Path.h" 24 #include <algorithm> 25 #include <cassert> 26 #include <cstddef> 27 #include <cstdint> 28 #include <cstdio> 29 #include <vector> 30 31 using namespace llvm; 32 using namespace dwarf; 33 34 void DWARFUnitSectionBase::parse(DWARFContext &C, const DWARFSection &Section) { 35 parseImpl(C, Section, C.getDebugAbbrev(), C.getRangeSection(), 36 C.getStringSection(), StringRef(), C.getAddrSection(), 37 C.getLineSection().Data, C.isLittleEndian(), false); 38 } 39 40 void DWARFUnitSectionBase::parseDWO(DWARFContext &C, 41 const DWARFSection &DWOSection, 42 DWARFUnitIndex *Index) { 43 parseImpl(C, DWOSection, C.getDebugAbbrevDWO(), C.getRangeDWOSection(), 44 C.getStringDWOSection(), C.getStringOffsetDWOSection(), 45 C.getAddrSection(), C.getLineDWOSection().Data, C.isLittleEndian(), 46 true); 47 } 48 49 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section, 50 const DWARFDebugAbbrev *DA, StringRef RS, StringRef SS, 51 StringRef SOS, StringRef AOS, StringRef LS, bool LE, 52 bool IsDWO, const DWARFUnitSectionBase &UnitSection, 53 const DWARFUnitIndex::Entry *IndexEntry) 54 : Context(DC), InfoSection(Section), Abbrev(DA), RangeSection(RS), 55 LineSection(LS), StringSection(SS), StringOffsetSection([&]() { 56 if (IndexEntry) 57 if (const auto *C = IndexEntry->getOffset(DW_SECT_STR_OFFSETS)) 58 return SOS.slice(C->Offset, C->Offset + C->Length); 59 return SOS; 60 }()), 61 AddrOffsetSection(AOS), isLittleEndian(LE), isDWO(IsDWO), 62 UnitSection(UnitSection), IndexEntry(IndexEntry) { 63 clear(); 64 } 65 66 DWARFUnit::~DWARFUnit() = default; 67 68 bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index, 69 uint64_t &Result) const { 70 uint32_t Offset = AddrOffsetSectionBase + Index * AddrSize; 71 if (AddrOffsetSection.size() < Offset + AddrSize) 72 return false; 73 DataExtractor DA(AddrOffsetSection, isLittleEndian, AddrSize); 74 Result = DA.getAddress(&Offset); 75 return true; 76 } 77 78 bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index, 79 uint32_t &Result) const { 80 // FIXME: string offset section entries are 8-byte for DWARF64. 81 const uint32_t ItemSize = 4; 82 uint32_t Offset = Index * ItemSize; 83 if (StringOffsetSection.size() < Offset + ItemSize) 84 return false; 85 DataExtractor DA(StringOffsetSection, isLittleEndian, 0); 86 Result = DA.getU32(&Offset); 87 return true; 88 } 89 90 bool DWARFUnit::extractImpl(DataExtractor debug_info, uint32_t *offset_ptr) { 91 Length = debug_info.getU32(offset_ptr); 92 Version = debug_info.getU16(offset_ptr); 93 uint64_t AbbrOffset; 94 if (Version >= 5) { 95 UnitType = debug_info.getU8(offset_ptr); 96 AddrSize = debug_info.getU8(offset_ptr); 97 AbbrOffset = debug_info.getU32(offset_ptr); 98 } else { 99 AbbrOffset = debug_info.getU32(offset_ptr); 100 AddrSize = debug_info.getU8(offset_ptr); 101 } 102 if (IndexEntry) { 103 if (AbbrOffset) 104 return false; 105 auto *UnitContrib = IndexEntry->getOffset(); 106 if (!UnitContrib || UnitContrib->Length != (Length + 4)) 107 return false; 108 auto *AbbrEntry = IndexEntry->getOffset(DW_SECT_ABBREV); 109 if (!AbbrEntry) 110 return false; 111 AbbrOffset = AbbrEntry->Offset; 112 } 113 114 bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1); 115 bool VersionOK = DWARFContext::isSupportedVersion(Version); 116 bool AddrSizeOK = AddrSize == 4 || AddrSize == 8; 117 118 if (!LengthOK || !VersionOK || !AddrSizeOK) 119 return false; 120 121 Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset); 122 return Abbrevs != nullptr; 123 } 124 125 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) { 126 clear(); 127 128 Offset = *offset_ptr; 129 130 if (debug_info.isValidOffset(*offset_ptr)) { 131 if (extractImpl(debug_info, offset_ptr)) 132 return true; 133 134 // reset the offset to where we tried to parse from if anything went wrong 135 *offset_ptr = Offset; 136 } 137 138 return false; 139 } 140 141 bool DWARFUnit::extractRangeList(uint32_t RangeListOffset, 142 DWARFDebugRangeList &RangeList) const { 143 // Require that compile unit is extracted. 144 assert(!DieArray.empty()); 145 DataExtractor RangesData(RangeSection, isLittleEndian, AddrSize); 146 uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset; 147 return RangeList.extract(RangesData, &ActualRangeListOffset); 148 } 149 150 void DWARFUnit::clear() { 151 Offset = 0; 152 Length = 0; 153 Version = 0; 154 Abbrevs = nullptr; 155 AddrSize = 0; 156 BaseAddr = 0; 157 RangeSectionBase = 0; 158 AddrOffsetSectionBase = 0; 159 clearDIEs(false); 160 DWO.reset(); 161 } 162 163 const char *DWARFUnit::getCompilationDir() { 164 return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr); 165 } 166 167 Optional<uint64_t> DWARFUnit::getDWOId() { 168 return toUnsigned(getUnitDIE().find(DW_AT_GNU_dwo_id)); 169 } 170 171 void DWARFUnit::extractDIEsToVector( 172 bool AppendCUDie, bool AppendNonCUDies, 173 std::vector<DWARFDebugInfoEntry> &Dies) const { 174 if (!AppendCUDie && !AppendNonCUDies) 175 return; 176 177 // Set the offset to that of the first DIE and calculate the start of the 178 // next compilation unit header. 179 uint32_t DIEOffset = Offset + getHeaderSize(); 180 uint32_t NextCUOffset = getNextUnitOffset(); 181 DWARFDebugInfoEntry DIE; 182 DataExtractor DebugInfoData = getDebugInfoExtractor(); 183 uint32_t Depth = 0; 184 bool IsCUDie = true; 185 186 while (DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset, 187 Depth)) { 188 if (IsCUDie) { 189 if (AppendCUDie) 190 Dies.push_back(DIE); 191 if (!AppendNonCUDies) 192 break; 193 // The average bytes per DIE entry has been seen to be 194 // around 14-20 so let's pre-reserve the needed memory for 195 // our DIE entries accordingly. 196 Dies.reserve(Dies.size() + getDebugInfoSize() / 14); 197 IsCUDie = false; 198 } else { 199 Dies.push_back(DIE); 200 } 201 202 if (const DWARFAbbreviationDeclaration *AbbrDecl = 203 DIE.getAbbreviationDeclarationPtr()) { 204 // Normal DIE 205 if (AbbrDecl->hasChildren()) 206 ++Depth; 207 } else { 208 // NULL DIE. 209 if (Depth > 0) 210 --Depth; 211 if (Depth == 0) 212 break; // We are done with this compile unit! 213 } 214 } 215 216 // Give a little bit of info if we encounter corrupt DWARF (our offset 217 // should always terminate at or before the start of the next compilation 218 // unit header). 219 if (DIEOffset > NextCUOffset) 220 fprintf(stderr, "warning: DWARF compile unit extends beyond its " 221 "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset); 222 } 223 224 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) { 225 if ((CUDieOnly && !DieArray.empty()) || 226 DieArray.size() > 1) 227 return 0; // Already parsed. 228 229 bool HasCUDie = !DieArray.empty(); 230 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray); 231 232 if (DieArray.empty()) 233 return 0; 234 235 // If CU DIE was just parsed, copy several attribute values from it. 236 if (!HasCUDie) { 237 DWARFDie UnitDie = getUnitDIE(); 238 auto BaseAddr = toAddress(UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc})); 239 if (BaseAddr) 240 setBaseAddress(*BaseAddr); 241 AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base), 0); 242 RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0); 243 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for 244 // skeleton CU DIE, so that DWARF users not aware of it are not broken. 245 } 246 247 return DieArray.size(); 248 } 249 250 DWARFUnit::DWOHolder::DWOHolder(StringRef DWOPath) { 251 auto Obj = object::ObjectFile::createObjectFile(DWOPath); 252 if (!Obj) { 253 // TODO: Actually report errors helpfully. 254 consumeError(Obj.takeError()); 255 return; 256 } 257 DWOFile = std::move(Obj.get()); 258 DWOContext.reset( 259 cast<DWARFContext>(new DWARFContextInMemory(*DWOFile.getBinary()))); 260 if (DWOContext->getNumDWOCompileUnits() > 0) 261 DWOU = DWOContext->getDWOCompileUnitAtIndex(0); 262 } 263 264 bool DWARFUnit::parseDWO() { 265 if (isDWO) 266 return false; 267 if (DWO.get()) 268 return false; 269 DWARFDie UnitDie = getUnitDIE(); 270 if (!UnitDie) 271 return false; 272 auto DWOFileName = dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name)); 273 if (!DWOFileName) 274 return false; 275 auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir)); 276 SmallString<16> AbsolutePath; 277 if (sys::path::is_relative(*DWOFileName) && CompilationDir && 278 *CompilationDir) { 279 sys::path::append(AbsolutePath, *CompilationDir); 280 } 281 sys::path::append(AbsolutePath, *DWOFileName); 282 DWO = llvm::make_unique<DWOHolder>(AbsolutePath); 283 DWARFUnit *DWOCU = DWO->getUnit(); 284 // Verify that compile unit in .dwo file is valid. 285 if (!DWOCU || DWOCU->getDWOId() != getDWOId()) { 286 DWO.reset(); 287 return false; 288 } 289 // Share .debug_addr and .debug_ranges section with compile unit in .dwo 290 DWOCU->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase); 291 auto DWORangesBase = UnitDie.getRangesBaseAttribute(); 292 DWOCU->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0); 293 return true; 294 } 295 296 void DWARFUnit::clearDIEs(bool KeepCUDie) { 297 if (DieArray.size() > (unsigned)KeepCUDie) { 298 // std::vectors never get any smaller when resized to a smaller size, 299 // or when clear() or erase() are called, the size will report that it 300 // is smaller, but the memory allocated remains intact (call capacity() 301 // to see this). So we need to create a temporary vector and swap the 302 // contents which will cause just the internal pointers to be swapped 303 // so that when temporary vector goes out of scope, it will destroy the 304 // contents. 305 std::vector<DWARFDebugInfoEntry> TmpArray; 306 DieArray.swap(TmpArray); 307 // Save at least the compile unit DIE 308 if (KeepCUDie) 309 DieArray.push_back(TmpArray.front()); 310 } 311 } 312 313 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) { 314 DWARFDie UnitDie = getUnitDIE(); 315 if (!UnitDie) 316 return; 317 // First, check if unit DIE describes address ranges for the whole unit. 318 const auto &CUDIERanges = UnitDie.getAddressRanges(); 319 if (!CUDIERanges.empty()) { 320 CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end()); 321 return; 322 } 323 324 // This function is usually called if there in no .debug_aranges section 325 // in order to produce a compile unit level set of address ranges that 326 // is accurate. If the DIEs weren't parsed, then we don't want all dies for 327 // all compile units to stay loaded when they weren't needed. So we can end 328 // up parsing the DWARF and then throwing them all away to keep memory usage 329 // down. 330 const bool ClearDIEs = extractDIEsIfNeeded(false) > 1; 331 getUnitDIE().collectChildrenAddressRanges(CURanges); 332 333 // Collect address ranges from DIEs in .dwo if necessary. 334 bool DWOCreated = parseDWO(); 335 if (DWO.get()) 336 DWO->getUnit()->collectAddressRanges(CURanges); 337 if (DWOCreated) 338 DWO.reset(); 339 340 // Keep memory down by clearing DIEs if this generate function 341 // caused them to be parsed. 342 if (ClearDIEs) 343 clearDIEs(true); 344 } 345 346 void DWARFUnit::updateAddressDieMap(DWARFDie Die) { 347 if (Die.isSubroutineDIE()) { 348 for (const auto &R : Die.getAddressRanges()) { 349 // Ignore 0-sized ranges. 350 if (R.first == R.second) 351 continue; 352 auto B = AddrDieMap.upper_bound(R.first); 353 if (B != AddrDieMap.begin() && R.first < (--B)->second.first) { 354 // The range is a sub-range of existing ranges, we need to split the 355 // existing range. 356 if (R.second < B->second.first) 357 AddrDieMap[R.second] = B->second; 358 if (R.first > B->first) 359 AddrDieMap[B->first].first = R.first; 360 } 361 AddrDieMap[R.first] = std::make_pair(R.second, Die); 362 } 363 } 364 // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to 365 // simplify the logic to update AddrDieMap. The child's range will always 366 // be equal or smaller than the parent's range. With this assumption, when 367 // adding one range into the map, it will at most split a range into 3 368 // sub-ranges. 369 for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling()) 370 updateAddressDieMap(Child); 371 } 372 373 DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) { 374 extractDIEsIfNeeded(false); 375 if (AddrDieMap.empty()) 376 updateAddressDieMap(getUnitDIE()); 377 auto R = AddrDieMap.upper_bound(Address); 378 if (R == AddrDieMap.begin()) 379 return DWARFDie(); 380 // upper_bound's previous item contains Address. 381 --R; 382 if (Address >= R->second.first) 383 return DWARFDie(); 384 return R->second.second; 385 } 386 387 void 388 DWARFUnit::getInlinedChainForAddress(uint64_t Address, 389 SmallVectorImpl<DWARFDie> &InlinedChain) { 390 assert(InlinedChain.empty()); 391 // Try to look for subprogram DIEs in the DWO file. 392 parseDWO(); 393 // First, find the subroutine that contains the given address (the leaf 394 // of inlined chain). 395 DWARFDie SubroutineDIE = 396 (DWO ? DWO->getUnit() : this)->getSubroutineForAddress(Address); 397 398 while (SubroutineDIE) { 399 if (SubroutineDIE.isSubroutineDIE()) 400 InlinedChain.push_back(SubroutineDIE); 401 SubroutineDIE = SubroutineDIE.getParent(); 402 } 403 } 404 405 const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context, 406 DWARFSectionKind Kind) { 407 if (Kind == DW_SECT_INFO) 408 return Context.getCUIndex(); 409 assert(Kind == DW_SECT_TYPES); 410 return Context.getTUIndex(); 411 } 412 413 DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) { 414 if (!Die) 415 return DWARFDie(); 416 const uint32_t Depth = Die->getDepth(); 417 // Unit DIEs always have a depth of zero and never have parents. 418 if (Depth == 0) 419 return DWARFDie(); 420 // Depth of 1 always means parent is the compile/type unit. 421 if (Depth == 1) 422 return getUnitDIE(); 423 // Look for previous DIE with a depth that is one less than the Die's depth. 424 const uint32_t ParentDepth = Depth - 1; 425 for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) { 426 if (DieArray[I].getDepth() == ParentDepth) 427 return DWARFDie(this, &DieArray[I]); 428 } 429 return DWARFDie(); 430 } 431 432 DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) { 433 if (!Die) 434 return DWARFDie(); 435 uint32_t Depth = Die->getDepth(); 436 // Unit DIEs always have a depth of zero and never have siblings. 437 if (Depth == 0) 438 return DWARFDie(); 439 // NULL DIEs don't have siblings. 440 if (Die->getAbbreviationDeclarationPtr() == nullptr) 441 return DWARFDie(); 442 443 // Find the next DIE whose depth is the same as the Die's depth. 444 for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx; 445 ++I) { 446 if (DieArray[I].getDepth() == Depth) 447 return DWARFDie(this, &DieArray[I]); 448 } 449 return DWARFDie(); 450 } 451