LLVM 19.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#include <algorithm>
25
26using namespace llvm;
27using namespace object;
28using namespace symbolize;
29
32 std::unique_ptr<DIContext> DICtx,
33 bool UntagAddresses) {
34 assert(DICtx);
35 std::unique_ptr<SymbolizableObjectFile> res(
36 new SymbolizableObjectFile(Obj, std::move(DICtx), UntagAddresses));
37 std::unique_ptr<DataExtractor> OpdExtractor;
38 uint64_t OpdAddress = 0;
39 // Find the .opd (function descriptor) section if any, for big-endian
40 // PowerPC64 ELF.
41 if (Obj->getArch() == Triple::ppc64) {
42 for (section_iterator Section : Obj->sections()) {
43 Expected<StringRef> NameOrErr = Section->getName();
44 if (!NameOrErr)
45 return NameOrErr.takeError();
46
47 if (*NameOrErr == ".opd") {
48 Expected<StringRef> E = Section->getContents();
49 if (!E)
50 return E.takeError();
51 OpdExtractor.reset(new DataExtractor(*E, Obj->isLittleEndian(),
52 Obj->getBytesInAddress()));
53 OpdAddress = Section->getAddress();
54 break;
55 }
56 }
57 }
58 std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
60 for (auto &P : Symbols)
61 if (Error E =
62 res->addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress))
63 return std::move(E);
64
65 // If this is a COFF object and we didn't find any symbols, try the export
66 // table.
67 if (Symbols.empty()) {
68 if (auto *CoffObj = dyn_cast<COFFObjectFile>(Obj))
69 if (Error E = res->addCoffExportSymbols(CoffObj))
70 return std::move(E);
71 }
72
73 std::vector<SymbolDesc> &SS = res->Symbols;
74 // Sort by (Addr,Size,Name). If several SymbolDescs share the same Addr,
75 // pick the one with the largest Size. This helps us avoid symbols with no
76 // size information (Size=0).
78 auto I = SS.begin(), E = SS.end(), J = SS.begin();
79 while (I != E) {
80 auto OI = I;
81 while (++I != E && OI->Addr == I->Addr) {
82 }
83 *J++ = I[-1];
84 }
85 SS.erase(J, SS.end());
86
87 return std::move(res);
88}
89
90SymbolizableObjectFile::SymbolizableObjectFile(const ObjectFile *Obj,
91 std::unique_ptr<DIContext> DICtx,
92 bool UntagAddresses)
93 : Module(Obj), DebugInfoContext(std::move(DICtx)),
94 UntagAddresses(UntagAddresses) {}
95
96namespace {
97
98struct OffsetNamePair {
101
102 bool operator<(const OffsetNamePair &R) const {
103 return Offset < R.Offset;
104 }
105};
106
107} // end anonymous namespace
108
109Error SymbolizableObjectFile::addCoffExportSymbols(
110 const COFFObjectFile *CoffObj) {
111 // Get all export names and offsets.
112 std::vector<OffsetNamePair> ExportSyms;
113 for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {
116 if (auto EC = Ref.getSymbolName(Name))
117 return EC;
118 if (auto EC = Ref.getExportRVA(Offset))
119 return EC;
120 ExportSyms.push_back(OffsetNamePair{Offset, Name});
121 }
122 if (ExportSyms.empty())
123 return Error::success();
124
125 // Sort by ascending offset.
126 array_pod_sort(ExportSyms.begin(), ExportSyms.end());
127
128 // Approximate the symbol sizes by assuming they run to the next symbol.
129 // FIXME: This assumes all exports are functions.
130 uint64_t ImageBase = CoffObj->getImageBase();
131 for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {
132 OffsetNamePair &Export = *I;
133 // FIXME: The last export has a one byte size now.
134 uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;
135 uint64_t SymbolStart = ImageBase + Export.Offset;
136 uint64_t SymbolSize = NextOffset - Export.Offset;
137 Symbols.push_back({SymbolStart, SymbolSize, Export.Name, 0});
138 }
139 return Error::success();
140}
141
142Error SymbolizableObjectFile::addSymbol(const SymbolRef &Symbol,
143 uint64_t SymbolSize,
144 DataExtractor *OpdExtractor,
145 uint64_t OpdAddress) {
146 // Avoid adding symbols from an unknown/undefined section.
147 const ObjectFile &Obj = *Symbol.getObject();
148 Expected<StringRef> SymbolNameOrErr = Symbol.getName();
149 if (!SymbolNameOrErr)
150 return SymbolNameOrErr.takeError();
151 StringRef SymbolName = *SymbolNameOrErr;
152
153 uint32_t ELFSymIdx =
154 Obj.isELF() ? ELFSymbolRef(Symbol).getRawDataRefImpl().d.b : 0;
155 Expected<section_iterator> Sec = Symbol.getSection();
156 if (!Sec || Obj.section_end() == *Sec) {
157 if (Obj.isELF()) {
158 // Store the (index, filename) pair for a file symbol.
159 ELFSymbolRef ESym(Symbol);
160 if (ESym.getELFType() == ELF::STT_FILE)
161 FileSymbols.emplace_back(ELFSymIdx, SymbolName);
162 }
163 return Error::success();
164 }
165
166 Expected<SymbolRef::Type> SymbolTypeOrErr = Symbol.getType();
167 if (!SymbolTypeOrErr)
168 return SymbolTypeOrErr.takeError();
169 SymbolRef::Type SymbolType = *SymbolTypeOrErr;
170 if (Obj.isELF()) {
171 // Ignore any symbols coming from sections that don't have runtime
172 // allocated memory.
173 if ((elf_section_iterator(*Sec)->getFlags() & ELF::SHF_ALLOC) == 0)
174 return Error::success();
175
176 // Allow function and data symbols. Additionally allow STT_NONE, which are
177 // common for functions defined in assembly.
178 uint8_t Type = ELFSymbolRef(Symbol).getELFType();
179 if (Type != ELF::STT_NOTYPE && Type != ELF::STT_FUNC &&
181 return Error::success();
182 // Some STT_NOTYPE symbols are not desired. This excludes STT_SECTION and
183 // ARM mapping symbols.
184 uint32_t Flags = cantFail(Symbol.getFlags());
185 if (Flags & SymbolRef::SF_FormatSpecific)
186 return Error::success();
187 } else if (SymbolType != SymbolRef::ST_Function &&
189 return Error::success();
190 }
191
192 Expected<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
193 if (!SymbolAddressOrErr)
194 return SymbolAddressOrErr.takeError();
195 uint64_t SymbolAddress = *SymbolAddressOrErr;
196 if (UntagAddresses) {
197 // For kernel addresses, bits 56-63 need to be set, so we sign extend bit 55
198 // into bits 56-63 instead of masking them out.
199 SymbolAddress &= (1ull << 56) - 1;
200 SymbolAddress = (int64_t(SymbolAddress) << 8) >> 8;
201 }
202 if (OpdExtractor) {
203 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
204 // function descriptors. The first word of the descriptor is a pointer to
205 // the function's code.
206 // For the purposes of symbolization, pretend the symbol's address is that
207 // of the function's code, not the descriptor.
208 uint64_t OpdOffset = SymbolAddress - OpdAddress;
209 if (OpdExtractor->isValidOffsetForAddress(OpdOffset))
210 SymbolAddress = OpdExtractor->getAddress(&OpdOffset);
211 }
212 // Mach-O symbol table names have leading underscore, skip it.
213 if (Module->isMachO())
214 SymbolName.consume_front("_");
215
216 if (Obj.isELF() && ELFSymbolRef(Symbol).getBinding() != ELF::STB_LOCAL)
217 ELFSymIdx = 0;
218 Symbols.push_back({SymbolAddress, SymbolSize, SymbolName, ELFSymIdx});
219 return Error::success();
220}
221
222// Return true if this is a 32-bit x86 PE COFF module.
224 auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
225 return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
226}
227
229 if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
230 return CoffObject->getImageBase();
231 return 0;
232}
233
234bool SymbolizableObjectFile::getNameFromSymbolTable(
235 uint64_t Address, std::string &Name, uint64_t &Addr, uint64_t &Size,
236 std::string &FileName) const {
237 SymbolDesc SD{Address, UINT64_C(-1), StringRef(), 0};
238 auto SymbolIterator = llvm::upper_bound(Symbols, SD);
239 if (SymbolIterator == Symbols.begin())
240 return false;
241 --SymbolIterator;
242 if (SymbolIterator->Size != 0 &&
243 SymbolIterator->Addr + SymbolIterator->Size <= Address)
244 return false;
245 Name = SymbolIterator->Name.str();
246 Addr = SymbolIterator->Addr;
247 Size = SymbolIterator->Size;
248
249 if (SymbolIterator->ELFLocalSymIdx != 0) {
250 // If this is an ELF local symbol, find the STT_FILE symbol preceding
251 // SymbolIterator to get the filename. The ELF spec requires the STT_FILE
252 // symbol (if present) precedes the other STB_LOCAL symbols for the file.
253 assert(Module->isELF());
254 auto It = llvm::upper_bound(
255 FileSymbols,
256 std::make_pair(SymbolIterator->ELFLocalSymIdx, StringRef()));
257 if (It != FileSymbols.begin())
258 FileName = It[-1].second.str();
259 }
260 return true;
261}
262
263bool SymbolizableObjectFile::shouldOverrideWithSymbolTable(
264 FunctionNameKind FNKind, bool UseSymbolTable) const {
265 // When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives
266 // better answers for linkage names than the DIContext. Otherwise, we are
267 // probably using PEs and PDBs, and we shouldn't do the override. PE files
268 // generally only contain the names of exported symbols.
269 return FNKind == FunctionNameKind::LinkageName && UseSymbolTable &&
270 isa<DWARFContext>(DebugInfoContext.get());
271}
272
275 DILineInfoSpecifier LineInfoSpecifier,
276 bool UseSymbolTable) const {
278 ModuleOffset.SectionIndex =
279 getModuleSectionIndexForAddress(ModuleOffset.Address);
280 DILineInfo LineInfo =
281 DebugInfoContext->getLineInfoForAddress(ModuleOffset, LineInfoSpecifier);
282
283 // Override function name from symbol table if necessary.
284 if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {
285 std::string FunctionName, FileName;
286 uint64_t Start, Size;
287 if (getNameFromSymbolTable(ModuleOffset.Address, FunctionName, Start, Size,
288 FileName)) {
289 LineInfo.FunctionName = FunctionName;
290 LineInfo.StartAddress = Start;
291 if (LineInfo.FileName == DILineInfo::BadString && !FileName.empty())
292 LineInfo.FileName = FileName;
293 }
294 }
295 return LineInfo;
296}
297
299 object::SectionedAddress ModuleOffset,
300 DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const {
302 ModuleOffset.SectionIndex =
303 getModuleSectionIndexForAddress(ModuleOffset.Address);
304 DIInliningInfo InlinedContext = DebugInfoContext->getInliningInfoForAddress(
305 ModuleOffset, LineInfoSpecifier);
306
307 // Make sure there is at least one frame in context.
308 if (InlinedContext.getNumberOfFrames() == 0)
309 InlinedContext.addFrame(DILineInfo());
310
311 // Override the function name in lower frame with name from symbol table.
312 if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {
313 std::string FunctionName, FileName;
314 uint64_t Start, Size;
315 if (getNameFromSymbolTable(ModuleOffset.Address, FunctionName, Start, Size,
316 FileName)) {
317 DILineInfo *LI = InlinedContext.getMutableFrame(
318 InlinedContext.getNumberOfFrames() - 1);
319 LI->FunctionName = FunctionName;
320 LI->StartAddress = Start;
321 if (LI->FileName == DILineInfo::BadString && !FileName.empty())
322 LI->FileName = FileName;
323 }
324 }
325
326 return InlinedContext;
327}
328
330 object::SectionedAddress ModuleOffset) const {
331 DIGlobal Res;
332 std::string FileName;
333 getNameFromSymbolTable(ModuleOffset.Address, Res.Name, Res.Start, Res.Size,
334 FileName);
335 Res.DeclFile = FileName;
336
337 // Try and get a better filename:lineno pair from the debuginfo, if present.
338 DILineInfo DL = DebugInfoContext->getLineInfoForDataAddress(ModuleOffset);
339 if (DL.Line != 0) {
340 Res.DeclFile = DL.FileName;
341 Res.DeclLine = DL.Line;
342 }
343 return Res;
344}
345
347 object::SectionedAddress ModuleOffset) const {
349 ModuleOffset.SectionIndex =
350 getModuleSectionIndexForAddress(ModuleOffset.Address);
351 return DebugInfoContext->getLocalsForAddress(ModuleOffset);
352}
353
354std::vector<object::SectionedAddress>
356 std::vector<object::SectionedAddress> Result;
357 for (const SymbolDesc &Sym : Symbols) {
358 if (Sym.Name.equals(Symbol)) {
359 uint64_t Addr = Sym.Addr;
360 if (Offset < Sym.Size)
361 Addr += Offset;
362 object::SectionedAddress A{Addr, getModuleSectionIndexForAddress(Addr)};
363 Result.push_back(A);
364 }
365 }
366 return Result;
367}
368
369/// Search for the first occurence of specified Address in ObjectFile.
370uint64_t SymbolizableObjectFile::getModuleSectionIndexForAddress(
371 uint64_t Address) const {
372
373 for (SectionRef Sec : Module->sections()) {
374 if (!Sec.isText() || Sec.isVirtual())
375 continue;
376
377 if (Address >= Sec.getAddress() &&
378 Address < Sec.getAddress() + Sec.getSize())
379 return Sec.getIndex();
380 }
381
383}
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:92
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:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
Error takeError()
Take ownership of the stored error.
Definition: Error.h:601
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:50
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:328
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:1157
@ STB_LOCAL
Definition: ELF.h:1310
@ STT_FUNC
Definition: ELF.h:1324
@ STT_NOTYPE
Definition: ELF.h:1322
@ STT_FILE
Definition: ELF.h:1326
@ STT_GNU_IFUNC
Definition: ELF.h:1329
@ STT_OBJECT
Definition: ELF.h:1323
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:456
bool operator<(int64_t V1, const APSInt &V2)
Definition: APSInt.h:361
void stable_sort(R &&Range)
Definition: STLExtras.h:2004
@ 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:1976
@ 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:749
DINameKind
A DINameKind is passed to name search methods to specify a preference regarding the type of name reso...
Definition: DIContext.h:140
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:1858
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:1616
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:118
uint64_t Size
Definition: DIContext.h:121
uint64_t Start
Definition: DIContext.h:120
std::string Name
Definition: DIContext.h:119
std::string DeclFile
Definition: DIContext.h:122
uint64_t DeclLine
Definition: DIContext.h:123
Controls which fields of DILineInfo container should be filled with data.
Definition: DIContext.h:144
FunctionNameKind FNKind
Definition: DIContext.h:158
A format-neutral container for source line information.
Definition: DIContext.h:32
static constexpr const char *const BadString
Definition: DIContext.h:34
std::optional< uint64_t > StartAddress
Definition: DIContext.h:48
std::string FileName
Definition: DIContext.h:37
std::string FunctionName
Definition: DIContext.h:38
static const uint64_t UndefSection
Definition: ObjectFile.h:146
struct llvm::object::DataRefImpl::@353 d