1 //===- DWARFDie.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/DWARFDie.h" 11 #include "llvm/ADT/None.h" 12 #include "llvm/ADT/Optional.h" 13 #include "llvm/ADT/StringRef.h" 14 #include "llvm/BinaryFormat/Dwarf.h" 15 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h" 16 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 17 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h" 18 #include "llvm/DebugInfo/DWARF/DWARFExpression.h" 19 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" 20 #include "llvm/DebugInfo/DWARF/DWARFUnit.h" 21 #include "llvm/Object/ObjectFile.h" 22 #include "llvm/Support/DataExtractor.h" 23 #include "llvm/Support/Format.h" 24 #include "llvm/Support/FormatVariadic.h" 25 #include "llvm/Support/MathExtras.h" 26 #include "llvm/Support/WithColor.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include <algorithm> 29 #include <cassert> 30 #include <cinttypes> 31 #include <cstdint> 32 #include <string> 33 #include <utility> 34 35 using namespace llvm; 36 using namespace dwarf; 37 using namespace object; 38 39 static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) { 40 OS << " ("; 41 do { 42 uint64_t Shift = countTrailingZeros(Val); 43 assert(Shift < 64 && "undefined behavior"); 44 uint64_t Bit = 1ULL << Shift; 45 auto PropName = ApplePropertyString(Bit); 46 if (!PropName.empty()) 47 OS << PropName; 48 else 49 OS << format("DW_APPLE_PROPERTY_0x%" PRIx64, Bit); 50 if (!(Val ^= Bit)) 51 break; 52 OS << ", "; 53 } while (true); 54 OS << ")"; 55 } 56 57 static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS, 58 const DWARFAddressRangesVector &Ranges, 59 unsigned AddressSize, unsigned Indent, 60 const DIDumpOptions &DumpOpts) { 61 ArrayRef<SectionName> SectionNames; 62 if (DumpOpts.Verbose) 63 SectionNames = Obj.getSectionNames(); 64 65 for (const DWARFAddressRange &R : Ranges) { 66 67 OS << '\n'; 68 OS.indent(Indent); 69 R.dump(OS, AddressSize); 70 71 if (SectionNames.empty() || R.SectionIndex == -1ULL) 72 continue; 73 74 StringRef Name = SectionNames[R.SectionIndex].Name; 75 OS << " \"" << Name << '\"'; 76 77 // Print section index if name is not unique. 78 if (!SectionNames[R.SectionIndex].IsNameUnique) 79 OS << format(" [%" PRIu64 "]", R.SectionIndex); 80 } 81 } 82 83 static void dumpLocation(raw_ostream &OS, DWARFFormValue &FormValue, 84 DWARFUnit *U, unsigned Indent, 85 DIDumpOptions DumpOpts) { 86 DWARFContext &Ctx = U->getContext(); 87 const DWARFObject &Obj = Ctx.getDWARFObj(); 88 const MCRegisterInfo *MRI = Ctx.getRegisterInfo(); 89 if (FormValue.isFormClass(DWARFFormValue::FC_Block) || 90 FormValue.isFormClass(DWARFFormValue::FC_Exprloc)) { 91 ArrayRef<uint8_t> Expr = *FormValue.getAsBlock(); 92 DataExtractor Data(StringRef((const char *)Expr.data(), Expr.size()), 93 Ctx.isLittleEndian(), 0); 94 DWARFExpression(Data, U->getVersion(), U->getAddressByteSize()) 95 .print(OS, MRI); 96 return; 97 } 98 99 FormValue.dump(OS, DumpOpts); 100 if (FormValue.isFormClass(DWARFFormValue::FC_SectionOffset)) { 101 const DWARFSection &LocSection = Obj.getLocSection(); 102 const DWARFSection &LocDWOSection = Obj.getLocDWOSection(); 103 uint32_t Offset = *FormValue.getAsSectionOffset(); 104 105 if (!LocSection.Data.empty()) { 106 DWARFDebugLoc DebugLoc; 107 DWARFDataExtractor Data(Obj, LocSection, Ctx.isLittleEndian(), 108 Obj.getAddressSize()); 109 auto LL = DebugLoc.parseOneLocationList(Data, &Offset); 110 if (LL) 111 LL->dump(OS, Ctx.isLittleEndian(), Obj.getAddressSize(), MRI, Indent); 112 else 113 OS << "error extracting location list."; 114 } else if (!LocDWOSection.Data.empty()) { 115 DataExtractor Data(LocDWOSection.Data, Ctx.isLittleEndian(), 0); 116 auto LL = DWARFDebugLocDWO::parseOneLocationList(Data, &Offset); 117 if (LL) 118 LL->dump(OS, Ctx.isLittleEndian(), Obj.getAddressSize(), MRI, Indent); 119 else 120 OS << "error extracting location list."; 121 } 122 } 123 } 124 125 /// Dump the name encoded in the type tag. 126 static void dumpTypeTagName(raw_ostream &OS, dwarf::Tag T) { 127 StringRef TagStr = TagString(T); 128 if (!TagStr.startswith("DW_TAG_") || !TagStr.endswith("_type")) 129 return; 130 OS << TagStr.substr(7, TagStr.size() - 12) << " "; 131 } 132 133 /// Recursively dump the DIE type name when applicable. 134 static void dumpTypeName(raw_ostream &OS, const DWARFDie &Die) { 135 DWARFDie D = Die.getAttributeValueAsReferencedDie(DW_AT_type); 136 137 if (!D.isValid()) 138 return; 139 140 if (const char *Name = D.getName(DINameKind::LinkageName)) { 141 OS << Name; 142 return; 143 } 144 145 // FIXME: We should have pretty printers per language. Currently we print 146 // everything as if it was C++ and fall back to the TAG type name. 147 const dwarf::Tag T = D.getTag(); 148 switch (T) { 149 case DW_TAG_array_type: 150 case DW_TAG_pointer_type: 151 case DW_TAG_ptr_to_member_type: 152 case DW_TAG_reference_type: 153 case DW_TAG_rvalue_reference_type: 154 break; 155 default: 156 dumpTypeTagName(OS, T); 157 } 158 159 // Follow the DW_AT_type if possible. 160 dumpTypeName(OS, D); 161 162 switch (T) { 163 case DW_TAG_array_type: 164 OS << "[]"; 165 break; 166 case DW_TAG_pointer_type: 167 OS << '*'; 168 break; 169 case DW_TAG_ptr_to_member_type: 170 OS << '*'; 171 break; 172 case DW_TAG_reference_type: 173 OS << '&'; 174 break; 175 case DW_TAG_rvalue_reference_type: 176 OS << "&&"; 177 break; 178 default: 179 break; 180 } 181 } 182 183 static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die, 184 uint32_t *OffsetPtr, dwarf::Attribute Attr, 185 dwarf::Form Form, unsigned Indent, 186 DIDumpOptions DumpOpts) { 187 if (!Die.isValid()) 188 return; 189 const char BaseIndent[] = " "; 190 OS << BaseIndent; 191 OS.indent(Indent + 2); 192 WithColor(OS, HighlightColor::Attribute) << formatv("{0}", Attr); 193 194 if (DumpOpts.Verbose || DumpOpts.ShowForm) 195 OS << formatv(" [{0}]", Form); 196 197 DWARFUnit *U = Die.getDwarfUnit(); 198 DWARFFormValue formValue(Form); 199 200 if (!formValue.extractValue(U->getDebugInfoExtractor(), OffsetPtr, 201 U->getFormParams(), U)) 202 return; 203 204 OS << "\t("; 205 206 StringRef Name; 207 std::string File; 208 auto Color = HighlightColor::Enumerator; 209 if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) { 210 Color = HighlightColor::String; 211 if (const auto *LT = U->getContext().getLineTableForUnit(U)) 212 if (LT->getFileNameByIndex( 213 formValue.getAsUnsignedConstant().getValue(), 214 U->getCompilationDir(), 215 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, File)) { 216 File = '"' + File + '"'; 217 Name = File; 218 } 219 } else if (Optional<uint64_t> Val = formValue.getAsUnsignedConstant()) 220 Name = AttributeValueString(Attr, *Val); 221 222 if (!Name.empty()) 223 WithColor(OS, Color) << Name; 224 else if (Attr == DW_AT_decl_line || Attr == DW_AT_call_line) 225 OS << *formValue.getAsUnsignedConstant(); 226 else if (Attr == DW_AT_high_pc && !DumpOpts.ShowForm && !DumpOpts.Verbose && 227 formValue.getAsUnsignedConstant()) { 228 if (DumpOpts.ShowAddresses) { 229 // Print the actual address rather than the offset. 230 uint64_t LowPC, HighPC, Index; 231 if (Die.getLowAndHighPC(LowPC, HighPC, Index)) 232 OS << format("0x%016" PRIx64, HighPC); 233 else 234 formValue.dump(OS, DumpOpts); 235 } 236 } else if (Attr == DW_AT_location || Attr == DW_AT_frame_base || 237 Attr == DW_AT_data_member_location || 238 Attr == DW_AT_GNU_call_site_value) 239 dumpLocation(OS, formValue, U, sizeof(BaseIndent) + Indent + 4, DumpOpts); 240 else 241 formValue.dump(OS, DumpOpts); 242 243 // We have dumped the attribute raw value. For some attributes 244 // having both the raw value and the pretty-printed value is 245 // interesting. These attributes are handled below. 246 if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin) { 247 if (const char *Name = Die.getAttributeValueAsReferencedDie(Attr).getName( 248 DINameKind::LinkageName)) 249 OS << " \"" << Name << '\"'; 250 } else if (Attr == DW_AT_type) { 251 OS << " \""; 252 dumpTypeName(OS, Die); 253 OS << '"'; 254 } else if (Attr == DW_AT_APPLE_property_attribute) { 255 if (Optional<uint64_t> OptVal = formValue.getAsUnsignedConstant()) 256 dumpApplePropertyAttribute(OS, *OptVal); 257 } else if (Attr == DW_AT_ranges) { 258 const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj(); 259 dumpRanges(Obj, OS, Die.getAddressRanges(), U->getAddressByteSize(), 260 sizeof(BaseIndent) + Indent + 4, DumpOpts); 261 } 262 263 OS << ")\n"; 264 } 265 266 bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; } 267 268 bool DWARFDie::isSubroutineDIE() const { 269 auto Tag = getTag(); 270 return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine; 271 } 272 273 Optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const { 274 if (!isValid()) 275 return None; 276 auto AbbrevDecl = getAbbreviationDeclarationPtr(); 277 if (AbbrevDecl) 278 return AbbrevDecl->getAttributeValue(getOffset(), Attr, *U); 279 return None; 280 } 281 282 Optional<DWARFFormValue> 283 DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const { 284 if (!isValid()) 285 return None; 286 auto AbbrevDecl = getAbbreviationDeclarationPtr(); 287 if (AbbrevDecl) { 288 for (auto Attr : Attrs) { 289 if (auto Value = AbbrevDecl->getAttributeValue(getOffset(), Attr, *U)) 290 return Value; 291 } 292 } 293 return None; 294 } 295 296 Optional<DWARFFormValue> 297 DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const { 298 if (!isValid()) 299 return None; 300 if (auto Value = find(Attrs)) 301 return Value; 302 if (auto Die = getAttributeValueAsReferencedDie(DW_AT_abstract_origin)) { 303 if (auto Value = Die.findRecursively(Attrs)) 304 return Value; 305 } 306 if (auto Die = getAttributeValueAsReferencedDie(DW_AT_specification)) { 307 if (auto Value = Die.findRecursively(Attrs)) 308 return Value; 309 } 310 return None; 311 } 312 313 DWARFDie 314 DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const { 315 if (auto SpecRef = toReference(find(Attr))) { 316 if (auto SpecUnit = U->getUnitSection().getUnitForOffset(*SpecRef)) 317 return SpecUnit->getDIEForOffset(*SpecRef); 318 } 319 return DWARFDie(); 320 } 321 322 Optional<uint64_t> DWARFDie::getRangesBaseAttribute() const { 323 return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base})); 324 } 325 326 Optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const { 327 if (auto FormValue = find(DW_AT_high_pc)) { 328 if (auto Address = FormValue->getAsAddress()) { 329 // High PC is an address. 330 return Address; 331 } 332 if (auto Offset = FormValue->getAsUnsignedConstant()) { 333 // High PC is an offset from LowPC. 334 return LowPC + *Offset; 335 } 336 } 337 return None; 338 } 339 340 bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC, 341 uint64_t &SectionIndex) const { 342 auto F = find(DW_AT_low_pc); 343 auto LowPcAddr = toAddress(F); 344 if (!LowPcAddr) 345 return false; 346 if (auto HighPcAddr = getHighPC(*LowPcAddr)) { 347 LowPC = *LowPcAddr; 348 HighPC = *HighPcAddr; 349 SectionIndex = F->getSectionIndex(); 350 return true; 351 } 352 return false; 353 } 354 355 DWARFAddressRangesVector DWARFDie::getAddressRanges() const { 356 if (isNULL()) 357 return DWARFAddressRangesVector(); 358 // Single range specified by low/high PC. 359 uint64_t LowPC, HighPC, Index; 360 if (getLowAndHighPC(LowPC, HighPC, Index)) 361 return {{LowPC, HighPC, Index}}; 362 363 // Multiple ranges from .debug_ranges section. 364 auto RangesOffset = toSectionOffset(find(DW_AT_ranges)); 365 if (RangesOffset) { 366 DWARFDebugRangeList RangeList; 367 if (U->extractRangeList(*RangesOffset, RangeList)) 368 return RangeList.getAbsoluteRanges(U->getBaseAddress()); 369 } 370 return DWARFAddressRangesVector(); 371 } 372 373 void DWARFDie::collectChildrenAddressRanges( 374 DWARFAddressRangesVector &Ranges) const { 375 if (isNULL()) 376 return; 377 if (isSubprogramDIE()) { 378 const auto &DIERanges = getAddressRanges(); 379 Ranges.insert(Ranges.end(), DIERanges.begin(), DIERanges.end()); 380 } 381 382 for (auto Child : children()) 383 Child.collectChildrenAddressRanges(Ranges); 384 } 385 386 bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const { 387 for (const auto &R : getAddressRanges()) { 388 if (R.LowPC <= Address && Address < R.HighPC) 389 return true; 390 } 391 return false; 392 } 393 394 const char *DWARFDie::getSubroutineName(DINameKind Kind) const { 395 if (!isSubroutineDIE()) 396 return nullptr; 397 return getName(Kind); 398 } 399 400 const char *DWARFDie::getName(DINameKind Kind) const { 401 if (!isValid() || Kind == DINameKind::None) 402 return nullptr; 403 // Try to get mangled name only if it was asked for. 404 if (Kind == DINameKind::LinkageName) { 405 if (auto Name = dwarf::toString( 406 findRecursively({DW_AT_MIPS_linkage_name, DW_AT_linkage_name}), 407 nullptr)) 408 return Name; 409 } 410 if (auto Name = dwarf::toString(findRecursively(DW_AT_name), nullptr)) 411 return Name; 412 return nullptr; 413 } 414 415 uint64_t DWARFDie::getDeclLine() const { 416 return toUnsigned(findRecursively(DW_AT_decl_line), 0); 417 } 418 419 void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine, 420 uint32_t &CallColumn, 421 uint32_t &CallDiscriminator) const { 422 CallFile = toUnsigned(find(DW_AT_call_file), 0); 423 CallLine = toUnsigned(find(DW_AT_call_line), 0); 424 CallColumn = toUnsigned(find(DW_AT_call_column), 0); 425 CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0); 426 } 427 428 /// Helper to dump a DIE with all of its parents, but no siblings. 429 static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent, 430 DIDumpOptions DumpOpts) { 431 if (!Die) 432 return Indent; 433 Indent = dumpParentChain(Die.getParent(), OS, Indent, DumpOpts); 434 Die.dump(OS, Indent, DumpOpts); 435 return Indent + 2; 436 } 437 438 void DWARFDie::dump(raw_ostream &OS, unsigned Indent, 439 DIDumpOptions DumpOpts) const { 440 if (!isValid()) 441 return; 442 DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor(); 443 const uint32_t Offset = getOffset(); 444 uint32_t offset = Offset; 445 if (DumpOpts.ShowParents) { 446 DumpOpts.ShowParents = false; 447 Indent = dumpParentChain(getParent(), OS, Indent, DumpOpts); 448 } 449 450 if (debug_info_data.isValidOffset(offset)) { 451 uint32_t abbrCode = debug_info_data.getULEB128(&offset); 452 if (DumpOpts.ShowAddresses) 453 WithColor(OS, HighlightColor::Address).get() 454 << format("\n0x%8.8x: ", Offset); 455 456 if (abbrCode) { 457 auto AbbrevDecl = getAbbreviationDeclarationPtr(); 458 if (AbbrevDecl) { 459 WithColor(OS, HighlightColor::Tag).get().indent(Indent) 460 << formatv("{0}", getTag()); 461 if (DumpOpts.Verbose) 462 OS << format(" [%u] %c", abbrCode, 463 AbbrevDecl->hasChildren() ? '*' : ' '); 464 OS << '\n'; 465 466 // Dump all data in the DIE for the attributes. 467 for (const auto &AttrSpec : AbbrevDecl->attributes()) { 468 if (AttrSpec.Form == DW_FORM_implicit_const) { 469 // We are dumping .debug_info section , 470 // implicit_const attribute values are not really stored here, 471 // but in .debug_abbrev section. So we just skip such attrs. 472 continue; 473 } 474 dumpAttribute(OS, *this, &offset, AttrSpec.Attr, AttrSpec.Form, 475 Indent, DumpOpts); 476 } 477 478 DWARFDie child = getFirstChild(); 479 if (DumpOpts.ShowChildren && DumpOpts.RecurseDepth > 0 && child) { 480 DumpOpts.RecurseDepth--; 481 while (child) { 482 child.dump(OS, Indent + 2, DumpOpts); 483 child = child.getSibling(); 484 } 485 } 486 } else { 487 OS << "Abbreviation code not found in 'debug_abbrev' class for code: " 488 << abbrCode << '\n'; 489 } 490 } else { 491 OS.indent(Indent) << "NULL\n"; 492 } 493 } 494 } 495 496 LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(llvm::errs(), 0); } 497 498 DWARFDie DWARFDie::getParent() const { 499 if (isValid()) 500 return U->getParent(Die); 501 return DWARFDie(); 502 } 503 504 DWARFDie DWARFDie::getSibling() const { 505 if (isValid()) 506 return U->getSibling(Die); 507 return DWARFDie(); 508 } 509 510 DWARFDie DWARFDie::getFirstChild() const { 511 if (isValid()) 512 return U->getFirstChild(Die); 513 return DWARFDie(); 514 } 515 516 iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const { 517 return make_range(attribute_iterator(*this, false), 518 attribute_iterator(*this, true)); 519 } 520 521 DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End) 522 : Die(D), AttrValue(0), Index(0) { 523 auto AbbrDecl = Die.getAbbreviationDeclarationPtr(); 524 assert(AbbrDecl && "Must have abbreviation declaration"); 525 if (End) { 526 // This is the end iterator so we set the index to the attribute count. 527 Index = AbbrDecl->getNumAttributes(); 528 } else { 529 // This is the begin iterator so we extract the value for this->Index. 530 AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize(); 531 updateForIndex(*AbbrDecl, 0); 532 } 533 } 534 535 void DWARFDie::attribute_iterator::updateForIndex( 536 const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) { 537 Index = I; 538 // AbbrDecl must be valid before calling this function. 539 auto NumAttrs = AbbrDecl.getNumAttributes(); 540 if (Index < NumAttrs) { 541 AttrValue.Attr = AbbrDecl.getAttrByIndex(Index); 542 // Add the previous byte size of any previous attribute value. 543 AttrValue.Offset += AttrValue.ByteSize; 544 AttrValue.Value.setForm(AbbrDecl.getFormByIndex(Index)); 545 uint32_t ParseOffset = AttrValue.Offset; 546 auto U = Die.getDwarfUnit(); 547 assert(U && "Die must have valid DWARF unit"); 548 bool b = AttrValue.Value.extractValue(U->getDebugInfoExtractor(), 549 &ParseOffset, U->getFormParams(), U); 550 (void)b; 551 assert(b && "extractValue cannot fail on fully parsed DWARF"); 552 AttrValue.ByteSize = ParseOffset - AttrValue.Offset; 553 } else { 554 assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only"); 555 AttrValue.clear(); 556 } 557 } 558 559 DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() { 560 if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr()) 561 updateForIndex(*AbbrDecl, Index + 1); 562 return *this; 563 } 564