Path: blob/main/contrib/llvm-project/llvm/lib/DebugInfo/Symbolize/SymbolizableObjectFile.cpp
35266 views
//===- SymbolizableObjectFile.cpp -----------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// Implementation of SymbolizableObjectFile class.9//10//===----------------------------------------------------------------------===//1112#include "llvm/DebugInfo/Symbolize/SymbolizableObjectFile.h"13#include "llvm/ADT/STLExtras.h"14#include "llvm/BinaryFormat/COFF.h"15#include "llvm/DebugInfo/DWARF/DWARFContext.h"16#include "llvm/Object/COFF.h"17#include "llvm/Object/ELFObjectFile.h"18#include "llvm/Object/ObjectFile.h"19#include "llvm/Object/SymbolSize.h"20#include "llvm/Support/Casting.h"21#include "llvm/Support/DataExtractor.h"22#include "llvm/TargetParser/Triple.h"23#include <algorithm>2425using namespace llvm;26using namespace object;27using namespace symbolize;2829Expected<std::unique_ptr<SymbolizableObjectFile>>30SymbolizableObjectFile::create(const object::ObjectFile *Obj,31std::unique_ptr<DIContext> DICtx,32bool UntagAddresses) {33assert(DICtx);34std::unique_ptr<SymbolizableObjectFile> res(35new SymbolizableObjectFile(Obj, std::move(DICtx), UntagAddresses));36std::unique_ptr<DataExtractor> OpdExtractor;37uint64_t OpdAddress = 0;38// Find the .opd (function descriptor) section if any, for big-endian39// PowerPC64 ELF.40if (Obj->getArch() == Triple::ppc64) {41for (section_iterator Section : Obj->sections()) {42Expected<StringRef> NameOrErr = Section->getName();43if (!NameOrErr)44return NameOrErr.takeError();4546if (*NameOrErr == ".opd") {47Expected<StringRef> E = Section->getContents();48if (!E)49return E.takeError();50OpdExtractor.reset(new DataExtractor(*E, Obj->isLittleEndian(),51Obj->getBytesInAddress()));52OpdAddress = Section->getAddress();53break;54}55}56}57std::vector<std::pair<SymbolRef, uint64_t>> Symbols =58computeSymbolSizes(*Obj);59for (auto &P : Symbols)60if (Error E =61res->addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress))62return std::move(E);6364// If this is a COFF object and we didn't find any symbols, try the export65// table.66if (Symbols.empty()) {67if (auto *CoffObj = dyn_cast<COFFObjectFile>(Obj))68if (Error E = res->addCoffExportSymbols(CoffObj))69return std::move(E);70}7172std::vector<SymbolDesc> &SS = res->Symbols;73// Sort by (Addr,Size,Name). If several SymbolDescs share the same Addr,74// pick the one with the largest Size. This helps us avoid symbols with no75// size information (Size=0).76llvm::stable_sort(SS);77auto I = SS.begin(), E = SS.end(), J = SS.begin();78while (I != E) {79auto OI = I;80while (++I != E && OI->Addr == I->Addr) {81}82*J++ = I[-1];83}84SS.erase(J, SS.end());8586return std::move(res);87}8889SymbolizableObjectFile::SymbolizableObjectFile(const ObjectFile *Obj,90std::unique_ptr<DIContext> DICtx,91bool UntagAddresses)92: Module(Obj), DebugInfoContext(std::move(DICtx)),93UntagAddresses(UntagAddresses) {}9495namespace {9697struct OffsetNamePair {98uint32_t Offset;99StringRef Name;100101bool operator<(const OffsetNamePair &R) const {102return Offset < R.Offset;103}104};105106} // end anonymous namespace107108Error SymbolizableObjectFile::addCoffExportSymbols(109const COFFObjectFile *CoffObj) {110// Get all export names and offsets.111std::vector<OffsetNamePair> ExportSyms;112for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {113StringRef Name;114uint32_t Offset;115if (auto EC = Ref.getSymbolName(Name))116return EC;117if (auto EC = Ref.getExportRVA(Offset))118return EC;119ExportSyms.push_back(OffsetNamePair{Offset, Name});120}121if (ExportSyms.empty())122return Error::success();123124// Sort by ascending offset.125array_pod_sort(ExportSyms.begin(), ExportSyms.end());126127// Approximate the symbol sizes by assuming they run to the next symbol.128// FIXME: This assumes all exports are functions.129uint64_t ImageBase = CoffObj->getImageBase();130for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {131OffsetNamePair &Export = *I;132// FIXME: The last export has a one byte size now.133uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;134uint64_t SymbolStart = ImageBase + Export.Offset;135uint64_t SymbolSize = NextOffset - Export.Offset;136Symbols.push_back({SymbolStart, SymbolSize, Export.Name, 0});137}138return Error::success();139}140141Error SymbolizableObjectFile::addSymbol(const SymbolRef &Symbol,142uint64_t SymbolSize,143DataExtractor *OpdExtractor,144uint64_t OpdAddress) {145// Avoid adding symbols from an unknown/undefined section.146const ObjectFile &Obj = *Symbol.getObject();147Expected<StringRef> SymbolNameOrErr = Symbol.getName();148if (!SymbolNameOrErr)149return SymbolNameOrErr.takeError();150StringRef SymbolName = *SymbolNameOrErr;151152uint32_t ELFSymIdx =153Obj.isELF() ? ELFSymbolRef(Symbol).getRawDataRefImpl().d.b : 0;154Expected<section_iterator> Sec = Symbol.getSection();155if (!Sec || Obj.section_end() == *Sec) {156if (Obj.isELF()) {157// Store the (index, filename) pair for a file symbol.158ELFSymbolRef ESym(Symbol);159if (ESym.getELFType() == ELF::STT_FILE)160FileSymbols.emplace_back(ELFSymIdx, SymbolName);161}162return Error::success();163}164165Expected<SymbolRef::Type> SymbolTypeOrErr = Symbol.getType();166if (!SymbolTypeOrErr)167return SymbolTypeOrErr.takeError();168SymbolRef::Type SymbolType = *SymbolTypeOrErr;169if (Obj.isELF()) {170// Ignore any symbols coming from sections that don't have runtime171// allocated memory.172if ((elf_section_iterator(*Sec)->getFlags() & ELF::SHF_ALLOC) == 0)173return Error::success();174175// Allow function and data symbols. Additionally allow STT_NONE, which are176// common for functions defined in assembly.177uint8_t Type = ELFSymbolRef(Symbol).getELFType();178if (Type != ELF::STT_NOTYPE && Type != ELF::STT_FUNC &&179Type != ELF::STT_OBJECT && Type != ELF::STT_GNU_IFUNC)180return Error::success();181// Some STT_NOTYPE symbols are not desired. This excludes STT_SECTION and182// ARM mapping symbols.183uint32_t Flags = cantFail(Symbol.getFlags());184if (Flags & SymbolRef::SF_FormatSpecific)185return Error::success();186} else if (SymbolType != SymbolRef::ST_Function &&187SymbolType != SymbolRef::ST_Data) {188return Error::success();189}190191Expected<uint64_t> SymbolAddressOrErr = Symbol.getAddress();192if (!SymbolAddressOrErr)193return SymbolAddressOrErr.takeError();194uint64_t SymbolAddress = *SymbolAddressOrErr;195if (UntagAddresses) {196// For kernel addresses, bits 56-63 need to be set, so we sign extend bit 55197// into bits 56-63 instead of masking them out.198SymbolAddress &= (1ull << 56) - 1;199SymbolAddress = (int64_t(SymbolAddress) << 8) >> 8;200}201if (OpdExtractor) {202// For big-endian PowerPC64 ELF, symbols in the .opd section refer to203// function descriptors. The first word of the descriptor is a pointer to204// the function's code.205// For the purposes of symbolization, pretend the symbol's address is that206// of the function's code, not the descriptor.207uint64_t OpdOffset = SymbolAddress - OpdAddress;208if (OpdExtractor->isValidOffsetForAddress(OpdOffset))209SymbolAddress = OpdExtractor->getAddress(&OpdOffset);210}211// Mach-O symbol table names have leading underscore, skip it.212if (Module->isMachO())213SymbolName.consume_front("_");214215if (Obj.isELF() && ELFSymbolRef(Symbol).getBinding() != ELF::STB_LOCAL)216ELFSymIdx = 0;217Symbols.push_back({SymbolAddress, SymbolSize, SymbolName, ELFSymIdx});218return Error::success();219}220221// Return true if this is a 32-bit x86 PE COFF module.222bool SymbolizableObjectFile::isWin32Module() const {223auto *CoffObject = dyn_cast<COFFObjectFile>(Module);224return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;225}226227uint64_t SymbolizableObjectFile::getModulePreferredBase() const {228if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))229return CoffObject->getImageBase();230return 0;231}232233bool SymbolizableObjectFile::getNameFromSymbolTable(234uint64_t Address, std::string &Name, uint64_t &Addr, uint64_t &Size,235std::string &FileName) const {236SymbolDesc SD{Address, UINT64_C(-1), StringRef(), 0};237auto SymbolIterator = llvm::upper_bound(Symbols, SD);238if (SymbolIterator == Symbols.begin())239return false;240--SymbolIterator;241if (SymbolIterator->Size != 0 &&242SymbolIterator->Addr + SymbolIterator->Size <= Address)243return false;244Name = SymbolIterator->Name.str();245Addr = SymbolIterator->Addr;246Size = SymbolIterator->Size;247248if (SymbolIterator->ELFLocalSymIdx != 0) {249// If this is an ELF local symbol, find the STT_FILE symbol preceding250// SymbolIterator to get the filename. The ELF spec requires the STT_FILE251// symbol (if present) precedes the other STB_LOCAL symbols for the file.252assert(Module->isELF());253auto It = llvm::upper_bound(254FileSymbols,255std::make_pair(SymbolIterator->ELFLocalSymIdx, StringRef()));256if (It != FileSymbols.begin())257FileName = It[-1].second.str();258}259return true;260}261262bool SymbolizableObjectFile::shouldOverrideWithSymbolTable(263FunctionNameKind FNKind, bool UseSymbolTable) const {264// When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives265// better answers for linkage names than the DIContext. Otherwise, we are266// probably using PEs and PDBs, and we shouldn't do the override. PE files267// generally only contain the names of exported symbols.268return FNKind == FunctionNameKind::LinkageName && UseSymbolTable &&269isa<DWARFContext>(DebugInfoContext.get());270}271272DILineInfo273SymbolizableObjectFile::symbolizeCode(object::SectionedAddress ModuleOffset,274DILineInfoSpecifier LineInfoSpecifier,275bool UseSymbolTable) const {276if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)277ModuleOffset.SectionIndex =278getModuleSectionIndexForAddress(ModuleOffset.Address);279DILineInfo LineInfo =280DebugInfoContext->getLineInfoForAddress(ModuleOffset, LineInfoSpecifier);281282// Override function name from symbol table if necessary.283if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {284std::string FunctionName, FileName;285uint64_t Start, Size;286if (getNameFromSymbolTable(ModuleOffset.Address, FunctionName, Start, Size,287FileName)) {288LineInfo.FunctionName = FunctionName;289LineInfo.StartAddress = Start;290if (LineInfo.FileName == DILineInfo::BadString && !FileName.empty())291LineInfo.FileName = FileName;292}293}294return LineInfo;295}296297DIInliningInfo SymbolizableObjectFile::symbolizeInlinedCode(298object::SectionedAddress ModuleOffset,299DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const {300if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)301ModuleOffset.SectionIndex =302getModuleSectionIndexForAddress(ModuleOffset.Address);303DIInliningInfo InlinedContext = DebugInfoContext->getInliningInfoForAddress(304ModuleOffset, LineInfoSpecifier);305306// Make sure there is at least one frame in context.307if (InlinedContext.getNumberOfFrames() == 0)308InlinedContext.addFrame(DILineInfo());309310// Override the function name in lower frame with name from symbol table.311if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {312std::string FunctionName, FileName;313uint64_t Start, Size;314if (getNameFromSymbolTable(ModuleOffset.Address, FunctionName, Start, Size,315FileName)) {316DILineInfo *LI = InlinedContext.getMutableFrame(317InlinedContext.getNumberOfFrames() - 1);318LI->FunctionName = FunctionName;319LI->StartAddress = Start;320if (LI->FileName == DILineInfo::BadString && !FileName.empty())321LI->FileName = FileName;322}323}324325return InlinedContext;326}327328DIGlobal SymbolizableObjectFile::symbolizeData(329object::SectionedAddress ModuleOffset) const {330DIGlobal Res;331std::string FileName;332getNameFromSymbolTable(ModuleOffset.Address, Res.Name, Res.Start, Res.Size,333FileName);334Res.DeclFile = FileName;335336// Try and get a better filename:lineno pair from the debuginfo, if present.337DILineInfo DL = DebugInfoContext->getLineInfoForDataAddress(ModuleOffset);338if (DL.Line != 0) {339Res.DeclFile = DL.FileName;340Res.DeclLine = DL.Line;341}342return Res;343}344345std::vector<DILocal> SymbolizableObjectFile::symbolizeFrame(346object::SectionedAddress ModuleOffset) const {347if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)348ModuleOffset.SectionIndex =349getModuleSectionIndexForAddress(ModuleOffset.Address);350return DebugInfoContext->getLocalsForAddress(ModuleOffset);351}352353std::vector<object::SectionedAddress>354SymbolizableObjectFile::findSymbol(StringRef Symbol, uint64_t Offset) const {355std::vector<object::SectionedAddress> Result;356for (const SymbolDesc &Sym : Symbols) {357if (Sym.Name == Symbol) {358uint64_t Addr = Sym.Addr;359if (Offset < Sym.Size)360Addr += Offset;361object::SectionedAddress A{Addr, getModuleSectionIndexForAddress(Addr)};362Result.push_back(A);363}364}365return Result;366}367368/// Search for the first occurence of specified Address in ObjectFile.369uint64_t SymbolizableObjectFile::getModuleSectionIndexForAddress(370uint64_t Address) const {371372for (SectionRef Sec : Module->sections()) {373if (!Sec.isText() || Sec.isVirtual())374continue;375376if (Address >= Sec.getAddress() &&377Address < Sec.getAddress() + Sec.getSize())378return Sec.getIndex();379}380381return object::SectionedAddress::UndefSection;382}383384385