LLVM 20.0.0git
SymbolizableObjectFile.cpp
Go to the documentation of this file.
1//===- SymbolizableObjectFile.cpp -----------------------------------------===//
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-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Implementation of SymbolizableObjectFile class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/STLExtras.h"
17#include "llvm/Object/COFF.h"
24
25using namespace llvm;
26using namespace object;
27using namespace symbolize;
28
31 std::unique_ptr<DIContext> DICtx,
32 bool UntagAddresses) {
33 assert(DICtx);
34 std::unique_ptr<SymbolizableObjectFile> res(
35 new SymbolizableObjectFile(Obj, std::move(DICtx), UntagAddresses));
36 std::unique_ptr<DataExtractor> OpdExtractor;
37 uint64_t OpdAddress = 0;
38 // Find the .opd (function descriptor) section if any, for big-endian
39 // PowerPC64 ELF.
40 if (Obj->getArch() == Triple::ppc64) {
41 for (section_iterator Section : Obj->sections()) {
42 Expected<StringRef> NameOrErr = Section->getName();
43 if (!NameOrErr)
44 return NameOrErr.takeError();
45
46 if (*NameOrErr == ".opd") {
47 Expected<StringRef> E = Section->getContents();
48 if (!E)
49 return E.takeError();
50 OpdExtractor.reset(new DataExtractor(*E, Obj->isLittleEndian(),
51 Obj->getBytesInAddress()));
52 OpdAddress = Section->getAddress();
53 break;
54 }
55 }
56 }
57 std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
59 for (auto &P : Symbols)
60 if (Error E =
61 res->addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress))
62 return std::move(E);
63
64 // If this is a COFF object and we didn't find any symbols, try the export
65 // table.
66 if (Symbols.empty()) {
67 if (auto *CoffObj = dyn_cast<COFFObjectFile>(Obj))
68 if (Error E = res->addCoffExportSymbols(CoffObj))
69 return std::move(E);
70 }
71
72 std::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 no
75 // size information (Size=0).
77 auto I = SS.begin(), E = SS.end(), J = SS.begin();
78 while (I != E) {
79 auto OI = I;
80 while (++I != E && OI->Addr == I->Addr) {
81 }
82 *J++ = I[-1];
83 }
84 SS.erase(J, SS.end());
85
86 return std::move(res);
87}
88
89SymbolizableObjectFile::SymbolizableObjectFile(const ObjectFile *Obj,
90 std::unique_ptr<DIContext> DICtx,
91 bool UntagAddresses)
92 : Module(Obj), DebugInfoContext(std::move(DICtx)),
93 UntagAddresses(UntagAddresses) {}
94
95namespace {
96
97struct OffsetNamePair {
100
101 bool operator<(const OffsetNamePair &R) const {
102 return Offset < R.Offset;
103 }
104};
105
106} // end anonymous namespace
107
108Error SymbolizableObjectFile::addCoffExportSymbols(
109 const COFFObjectFile *CoffObj) {
110 // Get all export names and offsets.
111 std::vector<OffsetNamePair> ExportSyms;
112 for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {
115 if (auto EC = Ref.getSymbolName(Name))
116 return EC;
117 if (auto EC = Ref.getExportRVA(Offset))
118 return EC;
119 ExportSyms.push_back(OffsetNamePair{Offset, Name});
120 }
121 if (ExportSyms.empty())
122 return Error::success();
123
124 // Sort by ascending offset.
125 array_pod_sort(ExportSyms.begin(), ExportSyms.end());
126
127 // Approximate the symbol sizes by assuming they run to the next symbol.
128 // FIXME: This assumes all exports are functions.
129 uint64_t ImageBase = CoffObj->getImageBase();
130 for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {
131 OffsetNamePair &Export = *I;
132 // FIXME: The last export has a one byte size now.
133 uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;
134 uint64_t SymbolStart = ImageBase + Export.Offset;
135 uint64_t SymbolSize = NextOffset - Export.Offset;
136 Symbols.push_back({SymbolStart, SymbolSize, Export.Name, 0});
137 }
138 return Error::success();
139}
140
141Error SymbolizableObjectFile::addSymbol(const SymbolRef &Symbol,
142 uint64_t SymbolSize,
143 DataExtractor *OpdExtractor,
144 uint64_t OpdAddress) {
145 // Avoid adding symbols from an unknown/undefined section.
146 const ObjectFile &Obj = *Symbol.getObject();
147 Expected<StringRef> SymbolNameOrErr = Symbol.getName();
148 if (!SymbolNameOrErr)
149 return SymbolNameOrErr.takeError();
150 StringRef SymbolName = *SymbolNameOrErr;
151
152 uint32_t ELFSymIdx =
153 Obj.isELF() ? ELFSymbolRef(Symbol).getRawDataRefImpl().d.b : 0;
154 Expected<section_iterator> Sec = Symbol.getSection();
155 if (!Sec || Obj.section_end() == *Sec) {
156 if (Obj.isELF()) {
157 // Store the (index, filename) pair for a file symbol.
158 ELFSymbolRef ESym(Symbol);
159 if (ESym.getELFType() == ELF::STT_FILE)
160 FileSymbols.emplace_back(ELFSymIdx, SymbolName);
161 }
162 return Error::success();
163 }
164
165 Expected<SymbolRef::Type> SymbolTypeOrErr = Symbol.getType();
166 if (!SymbolTypeOrErr)
167 return SymbolTypeOrErr.takeError();
168 SymbolRef::Type SymbolType = *SymbolTypeOrErr;
169 if (Obj.isELF()) {
170 // Ignore any symbols coming from sections that don't have runtime
171 // allocated memory.
172 if ((elf_section_iterator(*Sec)->getFlags() & ELF::SHF_ALLOC) == 0)
173 return Error::success();
174
175 // Allow function and data symbols. Additionally allow STT_NONE, which are
176 // common for functions defined in assembly.
178 if (Type != ELF::STT_NOTYPE && Type != ELF::STT_FUNC &&
180 return Error::success();
181 // Some STT_NOTYPE symbols are not desired. This excludes STT_SECTION and
182 // ARM mapping symbols.
183 uint32_t Flags = cantFail(Symbol.getFlags());
184 if (Flags & SymbolRef::SF_FormatSpecific)
185 return Error::success();
186 } else if (SymbolType != SymbolRef::ST_Function &&
188 return Error::success();
189 }
190
191 Expected<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
192 if (!SymbolAddressOrErr)
193 return SymbolAddressOrErr.takeError();
194 uint64_t SymbolAddress = *SymbolAddressOrErr;
195 if (UntagAddresses) {
196 // For kernel addresses, bits 56-63 need to be set, so we sign extend bit 55
197 // into bits 56-63 instead of masking them out.
198 SymbolAddress &= (1ull << 56) - 1;
199 SymbolAddress = (int64_t(SymbolAddress) << 8) >> 8;
200 }
201 if (OpdExtractor) {
202 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
203 // function descriptors. The first word of the descriptor is a pointer to
204 // the function's code.
205 // For the purposes of symbolization, pretend the symbol's address is that
206 // of the function's code, not the descriptor.
207 uint64_t OpdOffset = SymbolAddress - OpdAddress;
208 if (OpdExtractor->isValidOffsetForAddress(OpdOffset))
209 SymbolAddress = OpdExtractor->getAddress(&OpdOffset);
210 }
211 // Mach-O symbol table names have leading underscore, skip it.
212 if (Module->isMachO())
213 SymbolName.consume_front("_");
214
215 if (Obj.isELF() && ELFSymbolRef(Symbol).getBinding() != ELF::STB_LOCAL)
216 ELFSymIdx = 0;
217 Symbols.push_back({SymbolAddress, SymbolSize, SymbolName, ELFSymIdx});
218 return Error::success();
219}
220
221// Return true if this is a 32-bit x86 PE COFF module.
223 auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
224 return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
225}
226
228 if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
229 return CoffObject->getImageBase();
230 return 0;
231}
232
233bool SymbolizableObjectFile::getNameFromSymbolTable(
234 uint64_t Address, std::string &Name, uint64_t &Addr, uint64_t &Size,
235 std::string &FileName) const {
236 SymbolDesc SD{Address, UINT64_C(-1), StringRef(), 0};
237 auto SymbolIterator = llvm::upper_bound(Symbols, SD);
238 if (SymbolIterator == Symbols.begin())
239 return false;
240 --SymbolIterator;
241 if (SymbolIterator->Size != 0 &&
242 SymbolIterator->Addr + SymbolIterator->Size <= Address)
243 return false;
244 Name = SymbolIterator->Name.str();
245 Addr = SymbolIterator->Addr;
246 Size = SymbolIterator->Size;
247
248 if (SymbolIterator->ELFLocalSymIdx != 0) {
249 // If this is an ELF local symbol, find the STT_FILE symbol preceding
250 // SymbolIterator to get the filename. The ELF spec requires the STT_FILE
251 // symbol (if present) precedes the other STB_LOCAL symbols for the file.
252 assert(Module->isELF());
253 auto It = llvm::upper_bound(
254 FileSymbols,
255 std::make_pair(SymbolIterator->ELFLocalSymIdx, StringRef()));
256 if (It != FileSymbols.begin())
257 FileName = It[-1].second.str();
258 }
259 return true;
260}
261
262bool SymbolizableObjectFile::shouldOverrideWithSymbolTable(
263 FunctionNameKind FNKind, bool UseSymbolTable) const {
264 // When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives
265 // better answers for linkage names than the DIContext. Otherwise, we are
266 // probably using PEs and PDBs, and we shouldn't do the override. PE files
267 // generally only contain the names of exported symbols.
268 return FNKind == FunctionNameKind::LinkageName && UseSymbolTable &&
269 isa<DWARFContext>(DebugInfoContext.get());
270}
271
274 DILineInfoSpecifier LineInfoSpecifier,
275 bool UseSymbolTable) const {
277 ModuleOffset.SectionIndex =
278 getModuleSectionIndexForAddress(ModuleOffset.Address);
279 DILineInfo LineInfo =
280 DebugInfoContext->getLineInfoForAddress(ModuleOffset, LineInfoSpecifier);
281
282 // Override function name from symbol table if necessary.
283 if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {
284 std::string FunctionName, FileName;
285 uint64_t Start, Size;
286 if (getNameFromSymbolTable(ModuleOffset.Address, FunctionName, Start, Size,
287 FileName)) {
288 LineInfo.FunctionName = FunctionName;
289 LineInfo.StartAddress = Start;
290 if (LineInfo.FileName == DILineInfo::BadString && !FileName.empty())
291 LineInfo.FileName = FileName;
292 }
293 }
294 return LineInfo;
295}
296
298 object::SectionedAddress ModuleOffset,
299 DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const {
301 ModuleOffset.SectionIndex =
302 getModuleSectionIndexForAddress(ModuleOffset.Address);
303 DIInliningInfo InlinedContext = DebugInfoContext->getInliningInfoForAddress(
304 ModuleOffset, LineInfoSpecifier);
305
306 // Make sure there is at least one frame in context.
307 if (InlinedContext.getNumberOfFrames() == 0)
308 InlinedContext.addFrame(DILineInfo());
309
310 // Override the function name in lower frame with name from symbol table.
311 if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {
312 std::string FunctionName, FileName;
313 uint64_t Start, Size;
314 if (getNameFromSymbolTable(ModuleOffset.Address, FunctionName, Start, Size,
315 FileName)) {
316 DILineInfo *LI = InlinedContext.getMutableFrame(
317 InlinedContext.getNumberOfFrames() - 1);
318 LI->FunctionName = FunctionName;
319 LI->StartAddress = Start;
320 if (LI->FileName == DILineInfo::BadString && !FileName.empty())
321 LI->FileName = FileName;
322 }
323 }
324
325 return InlinedContext;
326}
327
329 object::SectionedAddress ModuleOffset) const {
330 DIGlobal Res;
331 std::string FileName;
332 getNameFromSymbolTable(ModuleOffset.Address, Res.Name, Res.Start, Res.Size,
333 FileName);
334 Res.DeclFile = FileName;
335
336 // Try and get a better filename:lineno pair from the debuginfo, if present.
337 DILineInfo DL = DebugInfoContext->getLineInfoForDataAddress(ModuleOffset);
338 if (DL.Line != 0) {
339 Res.DeclFile = DL.FileName;
340 Res.DeclLine = DL.Line;
341 }
342 return Res;
343}
344
346 object::SectionedAddress ModuleOffset) const {
348 ModuleOffset.SectionIndex =
349 getModuleSectionIndexForAddress(ModuleOffset.Address);
350 return DebugInfoContext->getLocalsForAddress(ModuleOffset);
351}
352
353std::vector<object::SectionedAddress>
355 std::vector<object::SectionedAddress> Result;
356 for (const SymbolDesc &Sym : Symbols) {
357 if (Sym.Name == Symbol) {
358 uint64_t Addr = Sym.Addr;
359 if (Offset < Sym.Size)
360 Addr += Offset;
361 object::SectionedAddress A{Addr, getModuleSectionIndexForAddress(Addr)};
362 Result.push_back(A);
363 }
364 }
365 return Result;
366}
367
368/// Search for the first occurence of specified Address in ObjectFile.
369uint64_t SymbolizableObjectFile::getModuleSectionIndexForAddress(
370 uint64_t Address) const {
371
372 for (SectionRef Sec : Module->sections()) {
373 if (!Sec.isText() || Sec.isVirtual())
374 continue;
375
376 if (Address >= Sec.getAddress() &&
377 Address < Sec.getAddress() + Sec.getSize())
378 return Sec.getIndex();
379 }
380
382}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
uint64_t Addr
std::string Name
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define I(x, y, z)
Definition: MD5.cpp:58
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
A format-neutral container for inlined code description.
Definition: DIContext.h:94
uint64_t getAddress(uint64_t *offset_ptr) const
Extract an pointer from *offset_ptr.
bool isValidOffsetForAddress(uint64_t offset) const
Test the availability of enough bytes of data for a pointer from offset.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
DataRefImpl getRawDataRefImpl() const
Definition: SymbolicFile.h:210
bool isLittleEndian() const
Definition: Binary.h:155
bool isELF() const
Definition: Binary.h:123
iterator_range< export_directory_iterator > export_directories() const
uint8_t getELFType() const
uint8_t getBinding() const
This class is the base class for all object file types.
Definition: ObjectFile.h:229
virtual section_iterator section_end() const =0
virtual uint8_t getBytesInAddress() const =0
The number of bytes used to represent an address in this object file format.
section_iterator_range sections() const
Definition: ObjectFile.h:329
virtual Triple::ArchType getArch() const =0
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81
This is a value type class that represents a single symbol in the list of symbols in the object file.
Definition: ObjectFile.h:168
DIGlobal symbolizeData(object::SectionedAddress ModuleOffset) const override
DILineInfo symbolizeCode(object::SectionedAddress ModuleOffset, DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const override
static Expected< std::unique_ptr< SymbolizableObjectFile > > create(const object::ObjectFile *Obj, std::unique_ptr< DIContext > DICtx, bool UntagAddresses)
std::vector< object::SectionedAddress > findSymbol(StringRef Symbol, uint64_t Offset) const override
std::vector< DILocal > symbolizeFrame(object::SectionedAddress ModuleOffset) const override
DIInliningInfo symbolizeInlinedCode(object::SectionedAddress ModuleOffset, DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const override
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
@ IMAGE_FILE_MACHINE_I386
Definition: COFF.h:104
@ SHF_ALLOC
Definition: ELF.h:1190
@ STB_LOCAL
Definition: ELF.h:1343
@ STT_FUNC
Definition: ELF.h:1357
@ STT_NOTYPE
Definition: ELF.h:1355
@ STT_FILE
Definition: ELF.h:1359
@ STT_GNU_IFUNC
Definition: ELF.h:1362
@ STT_OBJECT
Definition: ELF.h:1356
std::vector< std::pair< SymbolRef, uint64_t > > computeSymbolSizes(const ObjectFile &O)
Definition: SymbolSize.cpp:50
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
bool operator<(int64_t V1, const APSInt &V2)
Definition: APSInt.h:361
void stable_sort(R &&Range)
Definition: STLExtras.h:2037
@ Export
Export information to summary.
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1991
@ Ref
The access may reference the value stored in memory.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:756
DINameKind
A DINameKind is passed to name search methods to specify a preference regarding the type of name reso...
Definition: DIContext.h:142
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition: STLExtras.h:1624
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Container for description of a global variable.
Definition: DIContext.h:120
uint64_t Size
Definition: DIContext.h:123
uint64_t Start
Definition: DIContext.h:122
std::string Name
Definition: DIContext.h:121
std::string DeclFile
Definition: DIContext.h:124
uint64_t DeclLine
Definition: DIContext.h:125
Controls which fields of DILineInfo container should be filled with data.
Definition: DIContext.h:146
FunctionNameKind FNKind
Definition: DIContext.h:159
A format-neutral container for source line information.
Definition: DIContext.h:32
static constexpr const char *const BadString
Definition: DIContext.h:35
std::optional< uint64_t > StartAddress
Definition: DIContext.h:49
std::string FileName
Definition: DIContext.h:38
std::string FunctionName
Definition: DIContext.h:39
static const uint64_t UndefSection
Definition: ObjectFile.h:146
struct llvm::object::DataRefImpl::@371 d