773 lines · cpp
1//===-- SourcePrinter.cpp - source interleaving utilities ----------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements the LiveElementPrinter and SourcePrinter classes to10// keep track of DWARF info as the current address is updated, and print out the11// source file line and variable or inlined function liveness as needed.12//13//===----------------------------------------------------------------------===//14 15#include "SourcePrinter.h"16#include "llvm-objdump.h"17#include "llvm/ADT/SmallSet.h"18#include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h"19#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"20#include "llvm/Demangle/Demangle.h"21#include "llvm/Support/FormatVariadic.h"22 23#define DEBUG_TYPE "objdump"24 25namespace llvm {26namespace objdump {27 28bool InlinedFunction::liveAtAddress(object::SectionedAddress Addr) const {29 if (!Range.valid())30 return false;31 32 return Range.LowPC <= Addr.Address && Range.HighPC > Addr.Address;33}34 35void InlinedFunction::print(raw_ostream &OS, const MCRegisterInfo &MRI) const {36 const char *MangledCallerName = FuncDie.getName(DINameKind::LinkageName);37 if (!MangledCallerName)38 return;39 40 if (Demangle)41 OS << "inlined into " << demangle(MangledCallerName);42 else43 OS << "inlined into " << MangledCallerName;44}45 46void InlinedFunction::dump(raw_ostream &OS) const {47 OS << Name << " @ " << Range << ": ";48}49 50void InlinedFunction::printElementLine(raw_ostream &OS,51 object::SectionedAddress Addr,52 bool IsEnd) const {53 uint32_t CallFile, CallLine, CallColumn, CallDiscriminator;54 InlinedFuncDie.getCallerFrame(CallFile, CallLine, CallColumn,55 CallDiscriminator);56 const DWARFDebugLine::LineTable *LineTable =57 Unit->getContext().getLineTableForUnit(Unit);58 std::string FileName;59 if (!LineTable->hasFileAtIndex(CallFile))60 return;61 if (!LineTable->getFileNameByIndex(62 CallFile, Unit->getCompilationDir(),63 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FileName))64 return;65 66 if (FileName.empty())67 return;68 69 const char *MangledCallerName = FuncDie.getName(DINameKind::LinkageName);70 if (!MangledCallerName)71 return;72 73 std::string CallerName = MangledCallerName;74 std::string CalleeName = Name;75 if (Demangle) {76 CallerName = demangle(MangledCallerName);77 CalleeName = demangle(Name);78 }79 80 OS << "; " << FileName << ":" << CallLine << ":" << CallColumn << ": ";81 if (IsEnd)82 OS << "end of ";83 OS << CalleeName << " inlined into " << CallerName << "\n";84}85 86bool LiveVariable::liveAtAddress(object::SectionedAddress Addr) const {87 if (LocExpr.Range == std::nullopt)88 return false;89 return LocExpr.Range->SectionIndex == Addr.SectionIndex &&90 LocExpr.Range->LowPC <= Addr.Address &&91 LocExpr.Range->HighPC > Addr.Address;92}93 94void LiveVariable::print(raw_ostream &OS, const MCRegisterInfo &MRI) const {95 DataExtractor Data({LocExpr.Expr.data(), LocExpr.Expr.size()},96 Unit->getContext().isLittleEndian(), 0);97 DWARFExpression Expression(Data, Unit->getAddressByteSize());98 99 auto GetRegName = [&MRI, &OS](uint64_t DwarfRegNum, bool IsEH) -> StringRef {100 if (std::optional<MCRegister> LLVMRegNum =101 MRI.getLLVMRegNum(DwarfRegNum, IsEH))102 if (const char *RegName = MRI.getName(*LLVMRegNum))103 return StringRef(RegName);104 OS << "<unknown register " << DwarfRegNum << ">";105 return {};106 };107 108 printDwarfExpressionCompact(&Expression, OS, GetRegName);109}110 111void LiveVariable::dump(raw_ostream &OS) const {112 OS << Name << " @ " << LocExpr.Range << ": ";113}114 115void LiveElementPrinter::addInlinedFunction(DWARFDie FuncDie,116 DWARFDie InlinedFuncDie) {117 uint64_t FuncLowPC, FuncHighPC, SectionIndex;118 if (!InlinedFuncDie.getLowAndHighPC(FuncLowPC, FuncHighPC, SectionIndex))119 return;120 121 DWARFUnit *U = InlinedFuncDie.getDwarfUnit();122 const char *InlinedFuncName = InlinedFuncDie.getName(DINameKind::LinkageName);123 DWARFAddressRange Range{FuncLowPC, FuncHighPC, SectionIndex};124 // Add the new element to the main vector.125 LiveElements.emplace_back(std::make_unique<InlinedFunction>(126 InlinedFuncName, U, FuncDie, InlinedFuncDie, Range));127 128 LiveElement *LE = LiveElements.back().get();129 // Map the element's low address (LowPC) to its pointer for fast range start130 // lookup.131 LiveElementsByAddress[FuncLowPC].push_back(LE);132 // Map the element's high address (HighPC) to its pointer for fast range end133 // lookup.134 LiveElementsByEndAddress[FuncHighPC].push_back(LE);135 // Map the pointer to its DWARF discovery index for deterministic136 // ordering.137 ElementPtrToIndex[LE] = LiveElements.size() - 1;138}139 140/// Registers the most recently added LiveVariable into all data structures.141void LiveElementPrinter::registerNewVariable() {142 assert(143 !LiveElements.empty() &&144 "registerNewVariable called before element was added to LiveElements.");145 LiveVariable *CurrentVar =146 static_cast<LiveVariable *>(LiveElements.back().get());147 assert(ElementPtrToIndex.count(CurrentVar) == 0 &&148 "Element already registered!");149 150 // Map from a LiveElement pointer to its index in the LiveElements.151 ElementPtrToIndex[CurrentVar] = LiveElements.size() - 1;152 153 if (const std::optional<DWARFAddressRange> &Range =154 CurrentVar->getLocExpr().Range) {155 // Add the variable to address-based maps.156 LiveElementsByAddress[Range->LowPC].push_back(CurrentVar);157 LiveElementsByEndAddress[Range->HighPC].push_back(CurrentVar);158 }159}160 161void LiveElementPrinter::addVariable(DWARFDie FuncDie, DWARFDie VarDie) {162 uint64_t FuncLowPC, FuncHighPC, SectionIndex;163 FuncDie.getLowAndHighPC(FuncLowPC, FuncHighPC, SectionIndex);164 const char *VarName = VarDie.getName(DINameKind::ShortName);165 DWARFUnit *U = VarDie.getDwarfUnit();166 167 Expected<DWARFLocationExpressionsVector> Locs =168 VarDie.getLocations(dwarf::DW_AT_location);169 if (!Locs) {170 // If the variable doesn't have any locations, just ignore it. We don't171 // report an error or warning here as that could be noisy on optimised172 // code.173 consumeError(Locs.takeError());174 return;175 }176 177 for (const DWARFLocationExpression &LocExpr : *Locs) {178 if (LocExpr.Range) {179 LiveElements.emplace_back(180 std::make_unique<LiveVariable>(LocExpr, VarName, U, FuncDie));181 } else {182 // If the LocExpr does not have an associated range, it is valid for183 // the whole of the function.184 // TODO: technically it is not valid for any range covered by another185 // LocExpr, does that happen in reality?186 DWARFLocationExpression WholeFuncExpr{187 DWARFAddressRange(FuncLowPC, FuncHighPC, SectionIndex), LocExpr.Expr};188 LiveElements.emplace_back(189 std::make_unique<LiveVariable>(WholeFuncExpr, VarName, U, FuncDie));190 }191 192 // Register the new variable with all data structures.193 registerNewVariable();194 }195}196 197void LiveElementPrinter::addFunction(DWARFDie D) {198 for (const DWARFDie &Child : D.children()) {199 if (DbgVariables != DFDisabled &&200 (Child.getTag() == dwarf::DW_TAG_variable ||201 Child.getTag() == dwarf::DW_TAG_formal_parameter)) {202 addVariable(D, Child);203 } else if (DbgInlinedFunctions != DFDisabled &&204 Child.getTag() == dwarf::DW_TAG_inlined_subroutine) {205 addInlinedFunction(D, Child);206 addFunction(Child);207 } else208 addFunction(Child);209 }210}211 212// Get the column number (in characters) at which the first live element213// line should be printed.214unsigned LiveElementPrinter::getIndentLevel() const {215 return DbgIndent + getInstStartColumn(STI);216}217 218// Indent to the first live-range column to the right of the currently219// printed line, and return the index of that column.220// TODO: formatted_raw_ostream uses "column" to mean a number of characters221// since the last \n, and we use it to mean the number of slots in which we222// put live element lines. Pick a less overloaded word.223unsigned LiveElementPrinter::moveToFirstVarColumn(formatted_raw_ostream &OS) {224 // Logical column number: column zero is the first column we print in, each225 // logical column is 2 physical columns wide.226 unsigned FirstUnprintedLogicalColumn =227 std::max((int)(OS.getColumn() - getIndentLevel() + 1) / 2, 0);228 // Physical column number: the actual column number in characters, with229 // zero being the left-most side of the screen.230 unsigned FirstUnprintedPhysicalColumn =231 getIndentLevel() + FirstUnprintedLogicalColumn * 2;232 233 if (FirstUnprintedPhysicalColumn > OS.getColumn())234 OS.PadToColumn(FirstUnprintedPhysicalColumn);235 236 return FirstUnprintedLogicalColumn;237}238 239unsigned LiveElementPrinter::getOrCreateColumn(unsigned ElementIdx) {240 // Check if the element already has an assigned column.241 auto it = ElementToColumn.find(ElementIdx);242 if (it != ElementToColumn.end())243 return it->second;244 245 unsigned ColIdx;246 if (!FreeCols.empty()) {247 // Get the smallest available index from the set.248 ColIdx = *FreeCols.begin();249 // Remove the index from the set.250 FreeCols.erase(FreeCols.begin());251 } else {252 // No free columns, so create a new one.253 ColIdx = ActiveCols.size();254 ActiveCols.emplace_back();255 }256 257 // Assign the element to the column and update the map.258 ElementToColumn[ElementIdx] = ColIdx;259 ActiveCols[ColIdx].ElementIdx = ElementIdx;260 return ColIdx;261}262 263void LiveElementPrinter::freeColumn(unsigned ColIdx) {264 unsigned ElementIdx = ActiveCols[ColIdx].ElementIdx;265 266 // Clear the column's data.267 ActiveCols[ColIdx].clear();268 269 // Remove the element's entry from the map and add the column to the free270 // list.271 ElementToColumn.erase(ElementIdx);272 FreeCols.insert(ColIdx);273}274 275std::vector<unsigned>276LiveElementPrinter::getSortedActiveElementIndices() const {277 // Get all element indices that currently have an assigned column.278 std::vector<unsigned> Indices;279 for (const auto &Pair : ElementToColumn)280 Indices.push_back(Pair.first);281 282 // Sort by the DWARF discovery order.283 llvm::stable_sort(Indices);284 return Indices;285}286 287void LiveElementPrinter::dump() const {288 for (const std::unique_ptr<LiveElement> &LE : LiveElements) {289 LE->dump(dbgs());290 LE->print(dbgs(), MRI);291 dbgs() << "\n";292 }293}294 295void LiveElementPrinter::addCompileUnit(DWARFDie D) {296 if (D.getTag() == dwarf::DW_TAG_subprogram)297 addFunction(D);298 else299 for (const DWARFDie &Child : D.children())300 addFunction(Child);301}302 303/// Update to match the state of the instruction between ThisAddr and304/// NextAddr. In the common case, any live range active at ThisAddr is305/// live-in to the instruction, and any live range active at NextAddr is306/// live-out of the instruction. If IncludeDefinedVars is false, then live307/// ranges starting at NextAddr will be ignored.308void LiveElementPrinter::update(object::SectionedAddress ThisAddr,309 object::SectionedAddress NextAddr,310 bool IncludeDefinedVars) {311 // Exit early if only printing function limits.312 if (DbgInlinedFunctions == DFLimitsOnly)313 return;314 315 // Free columns identified in the previous cycle.316 for (unsigned ColIdx : ColumnsToFreeNextCycle)317 freeColumn(ColIdx);318 ColumnsToFreeNextCycle.clear();319 320 // Update status of active columns and collect those to free next cycle.321 for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx) {322 if (!ActiveCols[ColIdx].isActive())323 continue;324 325 const std::unique_ptr<LiveElement> &LE =326 LiveElements[ActiveCols[ColIdx].ElementIdx];327 ActiveCols[ColIdx].LiveIn = LE->liveAtAddress(ThisAddr);328 ActiveCols[ColIdx].LiveOut = LE->liveAtAddress(NextAddr);329 330 LLVM_DEBUG({331 std::string Name = Demangle ? demangle(LE->getName()) : LE->getName();332 dbgs() << "pass 1, " << ThisAddr.Address << "-" << NextAddr.Address333 << ", " << Name << ", Col " << ColIdx334 << ": LiveIn=" << ActiveCols[ColIdx].LiveIn335 << ", LiveOut=" << ActiveCols[ColIdx].LiveOut << "\n";336 });337 338 // If element is fully dead, deactivate column immediately.339 if (!ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut) {340 ActiveCols[ColIdx].ElementIdx = Column::NullElementIdx;341 continue;342 }343 344 // Mark for cleanup in the next cycle if range ends here.345 if (ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut)346 ColumnsToFreeNextCycle.push_back(ColIdx);347 }348 349 // Next, look for variables which don't already have a column, but which350 // are now live (those starting at ThisAddr or NextAddr).351 if (IncludeDefinedVars) {352 // Collect all elements starting at ThisAddr and NextAddr.353 std::vector<std::pair<unsigned, LiveElement *>> NewLiveElements;354 auto CollectNewElements = [&](const auto &It) {355 if (It == LiveElementsByAddress.end())356 return;357 358 const std::vector<LiveElement *> &ElementList = It->second;359 for (LiveElement *LE : ElementList) {360 auto IndexIt = ElementPtrToIndex.find(LE);361 assert(IndexIt != ElementPtrToIndex.end() &&362 "LiveElement in address map but missing from index map!");363 364 // Get the element index for sorting and column management.365 unsigned ElementIdx = IndexIt->second;366 // Skip elements that already have a column.367 if (ElementToColumn.count(ElementIdx))368 continue;369 370 bool LiveIn = LE->liveAtAddress(ThisAddr);371 bool LiveOut = LE->liveAtAddress(NextAddr);372 if (!LiveIn && !LiveOut)373 continue;374 375 NewLiveElements.emplace_back(ElementIdx, LE);376 }377 };378 379 // Collect elements starting at ThisAddr.380 CollectNewElements(LiveElementsByAddress.find(ThisAddr.Address));381 // Collect elements starting at NextAddr (the address immediately382 // following the instruction).383 CollectNewElements(LiveElementsByAddress.find(NextAddr.Address));384 // Sort elements by DWARF discovery order for deterministic column385 // assignment.386 llvm::stable_sort(NewLiveElements, [](const auto &A, const auto &B) {387 return A.first < B.first;388 });389 390 // Assign columns in deterministic order.391 for (const auto &ElementPair : NewLiveElements) {392 unsigned ElementIdx = ElementPair.first;393 // Skip if element was already added from the first range.394 if (ElementToColumn.count(ElementIdx))395 continue;396 397 LiveElement *LE = ElementPair.second;398 bool LiveIn = LE->liveAtAddress(ThisAddr);399 bool LiveOut = LE->liveAtAddress(NextAddr);400 401 // Assign or create a column.402 unsigned ColIdx = getOrCreateColumn(ElementIdx);403 LLVM_DEBUG({404 std::string Name = Demangle ? demangle(LE->getName()) : LE->getName();405 dbgs() << "pass 2, " << ThisAddr.Address << "-" << NextAddr.Address406 << ", " << Name << ", Col " << ColIdx << ": LiveIn=" << LiveIn407 << ", LiveOut=" << LiveOut << "\n";408 });409 410 ActiveCols[ColIdx].LiveIn = LiveIn;411 ActiveCols[ColIdx].LiveOut = LiveOut;412 ActiveCols[ColIdx].MustDrawLabel = true;413 414 // Mark for cleanup next cycle if range ends here.415 if (ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut)416 ColumnsToFreeNextCycle.push_back(ColIdx);417 }418 }419}420 421enum class LineChar {422 RangeStart,423 RangeMid,424 RangeEnd,425 LabelVert,426 LabelCornerNew,427 LabelCornerActive,428 LabelHoriz,429};430const char *LiveElementPrinter::getLineChar(LineChar C) const {431 bool IsASCII = DbgVariables == DFASCII || DbgInlinedFunctions == DFASCII;432 switch (C) {433 case LineChar::RangeStart:434 return IsASCII ? "^" : (const char *)u8"\u2548";435 case LineChar::RangeMid:436 return IsASCII ? "|" : (const char *)u8"\u2503";437 case LineChar::RangeEnd:438 return IsASCII ? "v" : (const char *)u8"\u253b";439 case LineChar::LabelVert:440 return IsASCII ? "|" : (const char *)u8"\u2502";441 case LineChar::LabelCornerNew:442 return IsASCII ? "/" : (const char *)u8"\u250c";443 case LineChar::LabelCornerActive:444 return IsASCII ? "|" : (const char *)u8"\u2520";445 case LineChar::LabelHoriz:446 return IsASCII ? "-" : (const char *)u8"\u2500";447 }448 llvm_unreachable("Unhandled LineChar enum");449}450 451/// Print live ranges to the right of an existing line. This assumes the452/// line is not an instruction, so doesn't start or end any live ranges, so453/// we only need to print active ranges or empty columns. If AfterInst is454/// true, this is being printed after the last instruction fed to update(),455/// otherwise this is being printed before it.456void LiveElementPrinter::printAfterOtherLine(formatted_raw_ostream &OS,457 bool AfterInst) {458 if (ActiveCols.size()) {459 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS);460 for (size_t ColIdx = FirstUnprintedColumn, End = ActiveCols.size();461 ColIdx < End; ++ColIdx) {462 if (ActiveCols[ColIdx].isActive()) {463 if ((AfterInst && ActiveCols[ColIdx].LiveOut) ||464 (!AfterInst && ActiveCols[ColIdx].LiveIn))465 OS << getLineChar(LineChar::RangeMid);466 else if (!AfterInst && ActiveCols[ColIdx].LiveOut)467 OS << getLineChar(LineChar::LabelVert);468 else469 OS << " ";470 }471 OS << " ";472 }473 }474 OS << "\n";475}476 477/// Print any live element range info needed to the right of a478/// non-instruction line of disassembly. This is where we print the element479/// names and expressions, with thin line-drawing characters connecting them480/// to the live range which starts at the next instruction. If MustPrint is481/// true, we have to print at least one line (with the continuation of any482/// already-active live ranges) because something has already been printed483/// earlier on this line.484void LiveElementPrinter::printBetweenInsts(formatted_raw_ostream &OS,485 bool MustPrint) {486 bool PrintedSomething = false;487 // Get all active elements, sorted by discovery order.488 std::vector<unsigned> SortedElementIndices = getSortedActiveElementIndices();489 // The outer loop iterates over the deterministic DWARF discovery order.490 for (unsigned ElementIdx : SortedElementIndices) {491 // Look up the physical column index (ColIdx) assigned to this492 // element. We use .at() because we are certain the element is active.493 unsigned ColIdx = ElementToColumn.at(ElementIdx);494 if (ActiveCols[ColIdx].isActive() && ActiveCols[ColIdx].MustDrawLabel) {495 // First we need to print the live range markers for any active496 // columns to the left of this one.497 OS.PadToColumn(getIndentLevel());498 for (unsigned ColIdx2 = 0; ColIdx2 < ColIdx; ++ColIdx2) {499 if (ActiveCols[ColIdx2].isActive()) {500 if (ActiveCols[ColIdx2].MustDrawLabel && !ActiveCols[ColIdx2].LiveIn)501 OS << getLineChar(LineChar::LabelVert) << " ";502 else503 OS << getLineChar(LineChar::RangeMid) << " ";504 } else505 OS << " ";506 }507 508 const std::unique_ptr<LiveElement> &LE = LiveElements[ElementIdx];509 // Then print the variable name and location of the new live range,510 // with box drawing characters joining it to the live range line.511 OS << getLineChar(ActiveCols[ColIdx].LiveIn ? LineChar::LabelCornerActive512 : LineChar::LabelCornerNew)513 << getLineChar(LineChar::LabelHoriz) << " ";514 515 std::string Name = Demangle ? demangle(LE->getName()) : LE->getName();516 WithColor(OS, raw_ostream::GREEN) << Name;517 OS << " = ";518 {519 WithColor ExprColor(OS, raw_ostream::CYAN);520 LE->print(OS, MRI);521 }522 523 // If there are any columns to the right of the expression we just524 // printed, then continue their live range lines.525 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS);526 for (unsigned ColIdx2 = FirstUnprintedColumn, End = ActiveCols.size();527 ColIdx2 < End; ++ColIdx2) {528 if (ActiveCols[ColIdx2].isActive() && ActiveCols[ColIdx2].LiveIn)529 OS << getLineChar(LineChar::RangeMid) << " ";530 else531 OS << " ";532 }533 534 OS << "\n";535 PrintedSomething = true;536 }537 }538 539 for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx)540 if (ActiveCols[ColIdx].isActive())541 ActiveCols[ColIdx].MustDrawLabel = false;542 543 // If we must print something (because we printed a line/column number),544 // but don't have any new variables to print, then print a line which545 // just continues any existing live ranges.546 if (MustPrint && !PrintedSomething)547 printAfterOtherLine(OS, false);548}549 550/// Print the live element ranges to the right of a disassembled instruction.551void LiveElementPrinter::printAfterInst(formatted_raw_ostream &OS) {552 if (!ActiveCols.size())553 return;554 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS);555 for (unsigned ColIdx = FirstUnprintedColumn, End = ActiveCols.size();556 ColIdx < End; ++ColIdx) {557 if (!ActiveCols[ColIdx].isActive())558 OS << " ";559 else if (ActiveCols[ColIdx].LiveIn && ActiveCols[ColIdx].LiveOut)560 OS << getLineChar(LineChar::RangeMid) << " ";561 else if (ActiveCols[ColIdx].LiveOut)562 OS << getLineChar(LineChar::RangeStart) << " ";563 else if (ActiveCols[ColIdx].LiveIn)564 OS << getLineChar(LineChar::RangeEnd) << " ";565 else566 llvm_unreachable("var must be live in or out!");567 }568}569 570void LiveElementPrinter::printBoundaryLine(formatted_raw_ostream &OS,571 object::SectionedAddress Addr,572 bool IsEnd) {573 // Only print the start/end line for inlined functions if DFLimitsOnly is574 // enabled.575 if (DbgInlinedFunctions != DFLimitsOnly)576 return;577 578 // Select the appropriate map based on whether we are checking the start579 // (LowPC) or end (HighPC) address.580 const auto &AddressMap =581 IsEnd ? LiveElementsByEndAddress : LiveElementsByAddress;582 583 // Use the map to find all elements that start/end at the given address.584 std::vector<unsigned> ElementIndices;585 auto It = AddressMap.find(Addr.Address);586 if (It != AddressMap.end()) {587 for (LiveElement *LE : It->second) {588 // Look up the element index from the pointer.589 auto IndexIt = ElementPtrToIndex.find(LE);590 assert(IndexIt != ElementPtrToIndex.end() &&591 "LiveElement found in address map but missing index!");592 ElementIndices.push_back(IndexIt->second);593 }594 }595 596 // Sort the indices to ensure deterministic output order (by DWARF discovery597 // order).598 llvm::stable_sort(ElementIndices);599 600 for (unsigned ElementIdx : ElementIndices) {601 LiveElement *LE = LiveElements[ElementIdx].get();602 LE->printElementLine(OS, Addr, IsEnd);603 }604}605 606bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {607 std::unique_ptr<MemoryBuffer> Buffer;608 if (LineInfo.Source) {609 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);610 } else {611 auto BufferOrError =612 MemoryBuffer::getFile(LineInfo.FileName, /*IsText=*/true);613 if (!BufferOrError) {614 if (MissingSources.insert(LineInfo.FileName).second)615 reportWarning("failed to find source " + LineInfo.FileName,616 Obj->getFileName());617 return false;618 }619 Buffer = std::move(*BufferOrError);620 }621 // Chomp the file to get lines622 const char *BufferStart = Buffer->getBufferStart(),623 *BufferEnd = Buffer->getBufferEnd();624 std::vector<StringRef> &Lines = LineCache[LineInfo.FileName];625 const char *Start = BufferStart;626 for (const char *I = BufferStart; I != BufferEnd; ++I)627 if (*I == '\n') {628 Lines.emplace_back(Start, I - Start - (BufferStart < I && I[-1] == '\r'));629 Start = I + 1;630 }631 if (Start < BufferEnd)632 Lines.emplace_back(Start, BufferEnd - Start);633 SourceCache[LineInfo.FileName] = std::move(Buffer);634 return true;635}636 637void SourcePrinter::printSourceLine(formatted_raw_ostream &OS,638 object::SectionedAddress Address,639 StringRef ObjectFilename,640 LiveElementPrinter &LEP,641 StringRef Delimiter) {642 if (!Symbolizer)643 return;644 645 DILineInfo LineInfo = DILineInfo();646 Expected<DILineInfo> ExpectedLineInfo =647 Symbolizer->symbolizeCode(*Obj, Address);648 if (ExpectedLineInfo) {649 LineInfo = *ExpectedLineInfo;650 } else if (!WarnedInvalidDebugInfo) {651 WarnedInvalidDebugInfo = true;652 // TODO Untested.653 reportWarning("failed to parse debug information: " +654 toString(ExpectedLineInfo.takeError()),655 ObjectFilename);656 }657 658 if (!objdump::Prefix.empty() &&659 sys::path::is_absolute_gnu(LineInfo.FileName)) {660 // FileName has at least one character since is_absolute_gnu is false for661 // an empty string.662 assert(!LineInfo.FileName.empty());663 if (PrefixStrip > 0) {664 uint32_t Level = 0;665 auto StrippedNameStart = LineInfo.FileName.begin();666 667 // Path.h iterator skips extra separators. Therefore it cannot be used668 // here to keep compatibility with GNU Objdump.669 for (auto Pos = StrippedNameStart + 1, End = LineInfo.FileName.end();670 Pos != End && Level < PrefixStrip; ++Pos) {671 if (sys::path::is_separator(*Pos)) {672 StrippedNameStart = Pos;673 ++Level;674 }675 }676 677 LineInfo.FileName =678 std::string(StrippedNameStart, LineInfo.FileName.end());679 }680 681 SmallString<128> FilePath;682 sys::path::append(FilePath, Prefix, LineInfo.FileName);683 684 LineInfo.FileName = std::string(FilePath);685 }686 687 if (PrintLines)688 printLines(OS, Address, LineInfo, Delimiter, LEP);689 if (PrintSource)690 printSources(OS, LineInfo, ObjectFilename, Delimiter, LEP);691 OldLineInfo = LineInfo;692}693 694void SourcePrinter::printLines(formatted_raw_ostream &OS,695 object::SectionedAddress Address,696 const DILineInfo &LineInfo, StringRef Delimiter,697 LiveElementPrinter &LEP) {698 bool PrintFunctionName = LineInfo.FunctionName != DILineInfo::BadString &&699 LineInfo.FunctionName != OldLineInfo.FunctionName;700 if (PrintFunctionName) {701 OS << Delimiter << LineInfo.FunctionName;702 // If demangling is successful, FunctionName will end with "()". Print it703 // only if demangling did not run or was unsuccessful.704 if (!StringRef(LineInfo.FunctionName).ends_with("()"))705 OS << "()";706 OS << ":\n";707 }708 if (LineInfo.FileName != DILineInfo::BadString && LineInfo.Line != 0 &&709 (OldLineInfo.Line != LineInfo.Line ||710 OldLineInfo.FileName != LineInfo.FileName || PrintFunctionName)) {711 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line;712 LEP.printBetweenInsts(OS, true);713 }714}715 716// Get the source line text for LineInfo:717// - use LineInfo::LineSource if available;718// - use LineCache if LineInfo::Source otherwise.719StringRef SourcePrinter::getLine(const DILineInfo &LineInfo,720 StringRef ObjectFilename) {721 if (LineInfo.LineSource)722 return LineInfo.LineSource.value();723 724 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())725 if (!cacheSource(LineInfo))726 return {};727 728 auto LineBuffer = LineCache.find(LineInfo.FileName);729 if (LineBuffer == LineCache.end())730 return {};731 732 if (LineInfo.Line > LineBuffer->second.size()) {733 reportWarning(734 formatv("debug info line number {0} exceeds the number of lines in {1}",735 LineInfo.Line, LineInfo.FileName),736 ObjectFilename);737 return {};738 }739 740 // Vector begins at 0, line numbers are non-zero741 return LineBuffer->second[LineInfo.Line - 1];742}743 744void SourcePrinter::printSources(formatted_raw_ostream &OS,745 const DILineInfo &LineInfo,746 StringRef ObjectFilename, StringRef Delimiter,747 LiveElementPrinter &LEP) {748 if (LineInfo.FileName == DILineInfo::BadString || LineInfo.Line == 0 ||749 (OldLineInfo.Line == LineInfo.Line &&750 OldLineInfo.FileName == LineInfo.FileName))751 return;752 753 StringRef Line = getLine(LineInfo, ObjectFilename);754 if (!Line.empty()) {755 OS << Delimiter << Line;756 LEP.printBetweenInsts(OS, true);757 }758}759 760SourcePrinter::SourcePrinter(const object::ObjectFile *Obj,761 StringRef DefaultArch)762 : Obj(Obj) {763 symbolize::LLVMSymbolizer::Options SymbolizerOpts;764 SymbolizerOpts.PrintFunctions =765 DILineInfoSpecifier::FunctionNameKind::LinkageName;766 SymbolizerOpts.Demangle = Demangle;767 SymbolizerOpts.DefaultArch = std::string(DefaultArch);768 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));769}770 771} // namespace objdump772} // namespace llvm773