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