LLVM  12.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 
13 #include "SymbolizableObjectFile.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/BinaryFormat/COFF.h"
20 #include "llvm/Object/COFF.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Object/SymbolSize.h"
23 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Error.h"
26 #include <algorithm>
27 #include <cstdint>
28 #include <memory>
29 #include <string>
30 #include <system_error>
31 #include <utility>
32 #include <vector>
33 
34 using namespace llvm;
35 using namespace object;
36 using namespace symbolize;
37 
39 SymbolizableObjectFile::create(const object::ObjectFile *Obj,
40  std::unique_ptr<DIContext> DICtx,
41  bool UntagAddresses) {
42  assert(DICtx);
43  std::unique_ptr<SymbolizableObjectFile> res(
44  new SymbolizableObjectFile(Obj, std::move(DICtx), UntagAddresses));
45  std::unique_ptr<DataExtractor> OpdExtractor;
46  uint64_t OpdAddress = 0;
47  // Find the .opd (function descriptor) section if any, for big-endian
48  // PowerPC64 ELF.
49  if (Obj->getArch() == Triple::ppc64) {
50  for (section_iterator Section : Obj->sections()) {
51  Expected<StringRef> NameOrErr = Section->getName();
52  if (!NameOrErr)
53  return NameOrErr.takeError();
54 
55  if (*NameOrErr == ".opd") {
56  Expected<StringRef> E = Section->getContents();
57  if (!E)
58  return E.takeError();
59  OpdExtractor.reset(new DataExtractor(*E, Obj->isLittleEndian(),
60  Obj->getBytesInAddress()));
61  OpdAddress = Section->getAddress();
62  break;
63  }
64  }
65  }
66  std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
67  computeSymbolSizes(*Obj);
68  for (auto &P : Symbols)
69  if (Error E =
70  res->addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress))
71  return std::move(E);
72 
73  // If this is a COFF object and we didn't find any symbols, try the export
74  // table.
75  if (Symbols.empty()) {
76  if (auto *CoffObj = dyn_cast<COFFObjectFile>(Obj))
77  if (Error E = res->addCoffExportSymbols(CoffObj))
78  return std::move(E);
79  }
80 
81  std::vector<std::pair<SymbolDesc, StringRef>> &Fs = res->Functions,
82  &Os = res->Objects;
83  auto Uniquify = [](std::vector<std::pair<SymbolDesc, StringRef>> &S) {
84  // Sort by (Addr,Size,Name). If several SymbolDescs share the same Addr,
85  // pick the one with the largest Size. This helps us avoid symbols with no
86  // size information (Size=0).
87  llvm::sort(S);
88  auto I = S.begin(), E = S.end(), J = S.begin();
89  while (I != E) {
90  auto OI = I;
91  while (++I != E && OI->first.Addr == I->first.Addr) {
92  }
93  *J++ = I[-1];
94  }
95  S.erase(J, S.end());
96  };
97  Uniquify(Fs);
98  Uniquify(Os);
99 
100  return std::move(res);
101 }
102 
103 SymbolizableObjectFile::SymbolizableObjectFile(const ObjectFile *Obj,
104  std::unique_ptr<DIContext> DICtx,
105  bool UntagAddresses)
106  : Module(Obj), DebugInfoContext(std::move(DICtx)),
107  UntagAddresses(UntagAddresses) {}
108 
109 namespace {
110 
111 struct OffsetNamePair {
113  StringRef Name;
114 
115  bool operator<(const OffsetNamePair &R) const {
116  return Offset < R.Offset;
117  }
118 };
119 
120 } // end anonymous namespace
121 
122 Error SymbolizableObjectFile::addCoffExportSymbols(
123  const COFFObjectFile *CoffObj) {
124  // Get all export names and offsets.
125  std::vector<OffsetNamePair> ExportSyms;
126  for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {
127  StringRef Name;
129  if (auto EC = Ref.getSymbolName(Name))
130  return EC;
131  if (auto EC = Ref.getExportRVA(Offset))
132  return EC;
133  ExportSyms.push_back(OffsetNamePair{Offset, Name});
134  }
135  if (ExportSyms.empty())
136  return Error::success();
137 
138  // Sort by ascending offset.
139  array_pod_sort(ExportSyms.begin(), ExportSyms.end());
140 
141  // Approximate the symbol sizes by assuming they run to the next symbol.
142  // FIXME: This assumes all exports are functions.
143  uint64_t ImageBase = CoffObj->getImageBase();
144  for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {
145  OffsetNamePair &Export = *I;
146  // FIXME: The last export has a one byte size now.
147  uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;
148  uint64_t SymbolStart = ImageBase + Export.Offset;
149  uint64_t SymbolSize = NextOffset - Export.Offset;
150  SymbolDesc SD = {SymbolStart, SymbolSize};
151  Functions.emplace_back(SD, Export.Name);
152  }
153  return Error::success();
154 }
155 
156 Error SymbolizableObjectFile::addSymbol(const SymbolRef &Symbol,
157  uint64_t SymbolSize,
158  DataExtractor *OpdExtractor,
159  uint64_t OpdAddress) {
160  // Avoid adding symbols from an unknown/undefined section.
161  const ObjectFile *Obj = Symbol.getObject();
162  Expected<section_iterator> Sec = Symbol.getSection();
163  if (!Sec || (Obj && Obj->section_end() == *Sec))
164  return Error::success();
165  Expected<SymbolRef::Type> SymbolTypeOrErr = Symbol.getType();
166  if (!SymbolTypeOrErr)
167  return SymbolTypeOrErr.takeError();
168  SymbolRef::Type SymbolType = *SymbolTypeOrErr;
169  if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
170  return Error::success();
171  Expected<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
172  if (!SymbolAddressOrErr)
173  return SymbolAddressOrErr.takeError();
174  uint64_t SymbolAddress = *SymbolAddressOrErr;
175  if (UntagAddresses) {
176  // For kernel addresses, bits 56-63 need to be set, so we sign extend bit 55
177  // into bits 56-63 instead of masking them out.
178  SymbolAddress &= (1ull << 56) - 1;
179  SymbolAddress = (int64_t(SymbolAddress) << 8) >> 8;
180  }
181  if (OpdExtractor) {
182  // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
183  // function descriptors. The first word of the descriptor is a pointer to
184  // the function's code.
185  // For the purposes of symbolization, pretend the symbol's address is that
186  // of the function's code, not the descriptor.
187  uint64_t OpdOffset = SymbolAddress - OpdAddress;
188  if (OpdExtractor->isValidOffsetForAddress(OpdOffset))
189  SymbolAddress = OpdExtractor->getAddress(&OpdOffset);
190  }
191  Expected<StringRef> SymbolNameOrErr = Symbol.getName();
192  if (!SymbolNameOrErr)
193  return SymbolNameOrErr.takeError();
194  StringRef SymbolName = *SymbolNameOrErr;
195  // Mach-O symbol table names have leading underscore, skip it.
196  if (Module->isMachO() && !SymbolName.empty() && SymbolName[0] == '_')
197  SymbolName = SymbolName.drop_front();
198  // FIXME: If a function has alias, there are two entries in symbol table
199  // with same address size. Make sure we choose the correct one.
200  auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
201  SymbolDesc SD = { SymbolAddress, SymbolSize };
202  M.emplace_back(SD, SymbolName);
203  return Error::success();
204 }
205 
206 // Return true if this is a 32-bit x86 PE COFF module.
207 bool SymbolizableObjectFile::isWin32Module() const {
208  auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
209  return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
210 }
211 
212 uint64_t SymbolizableObjectFile::getModulePreferredBase() const {
213  if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
214  return CoffObject->getImageBase();
215  return 0;
216 }
217 
218 bool SymbolizableObjectFile::getNameFromSymbolTable(SymbolRef::Type Type,
219  uint64_t Address,
220  std::string &Name,
221  uint64_t &Addr,
222  uint64_t &Size) const {
223  const auto &Symbols = Type == SymbolRef::ST_Function ? Functions : Objects;
224  std::pair<SymbolDesc, StringRef> SD{{Address, UINT64_C(-1)}, StringRef()};
225  auto SymbolIterator = llvm::upper_bound(Symbols, SD);
226  if (SymbolIterator == Symbols.begin())
227  return false;
228  --SymbolIterator;
229  if (SymbolIterator->first.Size != 0 &&
230  SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
231  return false;
232  Name = SymbolIterator->second.str();
233  Addr = SymbolIterator->first.Addr;
234  Size = SymbolIterator->first.Size;
235  return true;
236 }
237 
238 bool SymbolizableObjectFile::shouldOverrideWithSymbolTable(
239  FunctionNameKind FNKind, bool UseSymbolTable) const {
240  // When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives
241  // better answers for linkage names than the DIContext. Otherwise, we are
242  // probably using PEs and PDBs, and we shouldn't do the override. PE files
243  // generally only contain the names of exported symbols.
244  return FNKind == FunctionNameKind::LinkageName && UseSymbolTable &&
245  isa<DWARFContext>(DebugInfoContext.get());
246 }
247 
249 SymbolizableObjectFile::symbolizeCode(object::SectionedAddress ModuleOffset,
250  DILineInfoSpecifier LineInfoSpecifier,
251  bool UseSymbolTable) const {
253  ModuleOffset.SectionIndex =
254  getModuleSectionIndexForAddress(ModuleOffset.Address);
255  DILineInfo LineInfo =
256  DebugInfoContext->getLineInfoForAddress(ModuleOffset, LineInfoSpecifier);
257 
258  // Override function name from symbol table if necessary.
259  if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {
260  std::string FunctionName;
261  uint64_t Start, Size;
262  if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset.Address,
263  FunctionName, Start, Size)) {
264  LineInfo.FunctionName = FunctionName;
265  }
266  }
267  return LineInfo;
268 }
269 
270 DIInliningInfo SymbolizableObjectFile::symbolizeInlinedCode(
271  object::SectionedAddress ModuleOffset,
272  DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const {
274  ModuleOffset.SectionIndex =
275  getModuleSectionIndexForAddress(ModuleOffset.Address);
276  DIInliningInfo InlinedContext = DebugInfoContext->getInliningInfoForAddress(
277  ModuleOffset, LineInfoSpecifier);
278 
279  // Make sure there is at least one frame in context.
280  if (InlinedContext.getNumberOfFrames() == 0)
281  InlinedContext.addFrame(DILineInfo());
282 
283  // Override the function name in lower frame with name from symbol table.
284  if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {
285  std::string FunctionName;
286  uint64_t Start, Size;
287  if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset.Address,
288  FunctionName, Start, Size)) {
289  InlinedContext.getMutableFrame(InlinedContext.getNumberOfFrames() - 1)
290  ->FunctionName = FunctionName;
291  }
292  }
293 
294  return InlinedContext;
295 }
296 
297 DIGlobal SymbolizableObjectFile::symbolizeData(
298  object::SectionedAddress ModuleOffset) const {
299  DIGlobal Res;
300  getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset.Address, Res.Name,
301  Res.Start, Res.Size);
302  return Res;
303 }
304 
305 std::vector<DILocal> SymbolizableObjectFile::symbolizeFrame(
306  object::SectionedAddress ModuleOffset) const {
308  ModuleOffset.SectionIndex =
309  getModuleSectionIndexForAddress(ModuleOffset.Address);
310  return DebugInfoContext->getLocalsForAddress(ModuleOffset);
311 }
312 
313 /// Search for the first occurence of specified Address in ObjectFile.
314 uint64_t SymbolizableObjectFile::getModuleSectionIndexForAddress(
315  uint64_t Address) const {
316 
317  for (SectionRef Sec : Module->sections()) {
318  if (!Sec.isText() || Sec.isVirtual())
319  continue;
320 
321  if (Address >= Sec.getAddress() &&
322  Address < Sec.getAddress() + Sec.getSize())
323  return Sec.getIndex();
324  }
325 
327 }
LLVM_NODISCARD std::enable_if_t< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type > dyn_cast(const Y &Val)
Definition: Casting.h:334
DILineInfo * getMutableFrame(unsigned Index)
Definition: DIContext.h:93
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Expected< StringRef > getName() const
Definition: ObjectFile.h:384
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:67
Machine Debugify Module
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static const uint64_t UndefSection
Definition: ObjectFile.h:142
This class is the base class for all object file types.
Definition: ObjectFile.h:225
void addFrame(const DILineInfo &Frame)
Definition: DIContext.h:102
DINameKind
A DINameKind is passed to name search methods to specify a preference regarding the type of name reso...
Definition: DIContext.h:132
Error takeError()
Take ownership of the stored error.
Definition: Error.h:557
A format-neutral container for source line information.
Definition: DIContext.h:31
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
FunctionNameKind FNKind
Definition: DIContext.h:150
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the first N elements dropped.
Definition: StringRef.h:654
The access may reference the value stored in memory.
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:156
bool operator<(const SectionedAddress &LHS, const SectionedAddress &RHS)
Definition: ObjectFile.h:148
const ObjectFile * getObject() const
Definition: ObjectFile.h:412
uint64_t Start
Definition: DIContext.h:114
section_iterator_range sections() const
Definition: ObjectFile.h:319
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:1607
uint32_t getNumberOfFrames() const
Definition: DIContext.h:98
Expected< section_iterator > getSection() const
Get section this symbol is defined in reference to.
Definition: ObjectFile.h:404
#define P(N)
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:1391
virtual uint8_t getBytesInAddress() const =0
The number of bytes used to represent an address in this object file format.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
Controls which fields of DILineInfo container should be filled with data.
Definition: DIContext.h:136
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
A format-neutral container for inlined code description.
Definition: DIContext.h:82
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1433
Expected< uint64_t > getAddress() const
Returns the symbol virtual address (i.e.
Definition: ObjectFile.h:388
bool isLittleEndian() const
Definition: Binary.h:146
uint16_t getMachine() const
Definition: COFF.h:822
static ErrorSuccess success()
Create a success value.
Definition: Error.h:332
Expected< SymbolRef::Type > getType() const
Definition: ObjectFile.h:408
std::string Name
Definition: DIContext.h:113
std::string FunctionName
Definition: DIContext.h:37
virtual Triple::ArchType getArch() const =0
uint64_t Size
Definition: DIContext.h:115
std::vector< std::pair< SymbolRef, uint64_t > > computeSymbolSizes(const ObjectFile &O)
Definition: SymbolSize.cpp:46
This is a value type class that represents a single symbol in the list of symbols in the object file...
Definition: ObjectFile.h:164
virtual section_iterator section_end() const =0
#define I(x, y, z)
Definition: MD5.cpp:59
iterator_range< export_directory_iterator > export_directories() const
uint32_t Size
Definition: Profile.cpp:46
uint64_t getAddress(uint64_t *offset_ptr) const
Extract an pointer from *offset_ptr.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
Container for description of a global variable.
Definition: DIContext.h:112
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:80
bool isValidOffsetForAddress(uint64_t offset) const
Test the availability of enough bytes of data for a pointer from offset.