LLVM  9.0.0svn
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 
40  return DILineInfoSpecifier(
42 }
43 
45 SymbolizableObjectFile::create(object::ObjectFile *Obj,
46  std::unique_ptr<DIContext> DICtx) {
47  std::unique_ptr<SymbolizableObjectFile> res(
48  new SymbolizableObjectFile(Obj, std::move(DICtx)));
49  std::unique_ptr<DataExtractor> OpdExtractor;
50  uint64_t OpdAddress = 0;
51  // Find the .opd (function descriptor) section if any, for big-endian
52  // PowerPC64 ELF.
53  if (Obj->getArch() == Triple::ppc64) {
54  for (section_iterator Section : Obj->sections()) {
57  if (auto EC = Section->getName(Name))
58  return EC;
59  if (Name == ".opd") {
60  if (auto EC = Section->getContents(Data))
61  return EC;
62  OpdExtractor.reset(new DataExtractor(Data, Obj->isLittleEndian(),
63  Obj->getBytesInAddress()));
64  OpdAddress = Section->getAddress();
65  break;
66  }
67  }
68  }
69  std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
70  computeSymbolSizes(*Obj);
71  for (auto &P : Symbols)
72  res->addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress);
73 
74  // If this is a COFF object and we didn't find any symbols, try the export
75  // table.
76  if (Symbols.empty()) {
77  if (auto *CoffObj = dyn_cast<COFFObjectFile>(Obj))
78  if (auto EC = res->addCoffExportSymbols(CoffObj))
79  return EC;
80  }
81  return std::move(res);
82 }
83 
84 SymbolizableObjectFile::SymbolizableObjectFile(ObjectFile *Obj,
85  std::unique_ptr<DIContext> DICtx)
86  : Module(Obj), DebugInfoContext(std::move(DICtx)) {}
87 
88 namespace {
89 
90 struct OffsetNamePair {
93 
94  bool operator<(const OffsetNamePair &R) const {
95  return Offset < R.Offset;
96  }
97 };
98 
99 } // end anonymous namespace
100 
101 std::error_code SymbolizableObjectFile::addCoffExportSymbols(
102  const COFFObjectFile *CoffObj) {
103  // Get all export names and offsets.
104  std::vector<OffsetNamePair> ExportSyms;
105  for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {
106  StringRef Name;
108  if (auto EC = Ref.getSymbolName(Name))
109  return EC;
110  if (auto EC = Ref.getExportRVA(Offset))
111  return EC;
112  ExportSyms.push_back(OffsetNamePair{Offset, Name});
113  }
114  if (ExportSyms.empty())
115  return std::error_code();
116 
117  // Sort by ascending offset.
118  array_pod_sort(ExportSyms.begin(), ExportSyms.end());
119 
120  // Approximate the symbol sizes by assuming they run to the next symbol.
121  // FIXME: This assumes all exports are functions.
122  uint64_t ImageBase = CoffObj->getImageBase();
123  for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {
124  OffsetNamePair &Export = *I;
125  // FIXME: The last export has a one byte size now.
126  uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;
127  uint64_t SymbolStart = ImageBase + Export.Offset;
128  uint64_t SymbolSize = NextOffset - Export.Offset;
129  SymbolDesc SD = {SymbolStart, SymbolSize};
130  Functions.insert(std::make_pair(SD, Export.Name));
131  }
132  return std::error_code();
133 }
134 
135 std::error_code SymbolizableObjectFile::addSymbol(const SymbolRef &Symbol,
136  uint64_t SymbolSize,
137  DataExtractor *OpdExtractor,
138  uint64_t OpdAddress) {
139  // Avoid adding symbols from an unknown/undefined section.
140  const ObjectFile *Obj = Symbol.getObject();
141  Expected<section_iterator> Sec = Symbol.getSection();
142  if (!Sec || (Obj && Obj->section_end() == *Sec))
143  return std::error_code();
144  Expected<SymbolRef::Type> SymbolTypeOrErr = Symbol.getType();
145  if (!SymbolTypeOrErr)
146  return errorToErrorCode(SymbolTypeOrErr.takeError());
147  SymbolRef::Type SymbolType = *SymbolTypeOrErr;
148  if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
149  return std::error_code();
150  Expected<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
151  if (!SymbolAddressOrErr)
152  return errorToErrorCode(SymbolAddressOrErr.takeError());
153  uint64_t SymbolAddress = *SymbolAddressOrErr;
154  if (OpdExtractor) {
155  // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
156  // function descriptors. The first word of the descriptor is a pointer to
157  // the function's code.
158  // For the purposes of symbolization, pretend the symbol's address is that
159  // of the function's code, not the descriptor.
160  uint64_t OpdOffset = SymbolAddress - OpdAddress;
161  uint32_t OpdOffset32 = OpdOffset;
162  if (OpdOffset == OpdOffset32 &&
163  OpdExtractor->isValidOffsetForAddress(OpdOffset32))
164  SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
165  }
166  Expected<StringRef> SymbolNameOrErr = Symbol.getName();
167  if (!SymbolNameOrErr)
168  return errorToErrorCode(SymbolNameOrErr.takeError());
169  StringRef SymbolName = *SymbolNameOrErr;
170  // Mach-O symbol table names have leading underscore, skip it.
171  if (Module->isMachO() && !SymbolName.empty() && SymbolName[0] == '_')
172  SymbolName = SymbolName.drop_front();
173  // FIXME: If a function has alias, there are two entries in symbol table
174  // with same address size. Make sure we choose the correct one.
175  auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
176  SymbolDesc SD = { SymbolAddress, SymbolSize };
177  M.insert(std::make_pair(SD, SymbolName));
178  return std::error_code();
179 }
180 
181 // Return true if this is a 32-bit x86 PE COFF module.
182 bool SymbolizableObjectFile::isWin32Module() const {
183  auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
184  return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
185 }
186 
187 uint64_t SymbolizableObjectFile::getModulePreferredBase() const {
188  if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
189  return CoffObject->getImageBase();
190  return 0;
191 }
192 
193 bool SymbolizableObjectFile::getNameFromSymbolTable(SymbolRef::Type Type,
194  uint64_t Address,
195  std::string &Name,
196  uint64_t &Addr,
197  uint64_t &Size) const {
198  const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
199  if (SymbolMap.empty())
200  return false;
201  SymbolDesc SD = { Address, Address };
202  auto SymbolIterator = SymbolMap.upper_bound(SD);
203  if (SymbolIterator == SymbolMap.begin())
204  return false;
205  --SymbolIterator;
206  if (SymbolIterator->first.Size != 0 &&
207  SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
208  return false;
209  Name = SymbolIterator->second.str();
210  Addr = SymbolIterator->first.Addr;
211  Size = SymbolIterator->first.Size;
212  return true;
213 }
214 
215 bool SymbolizableObjectFile::shouldOverrideWithSymbolTable(
216  FunctionNameKind FNKind, bool UseSymbolTable) const {
217  // When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives
218  // better answers for linkage names than the DIContext. Otherwise, we are
219  // probably using PEs and PDBs, and we shouldn't do the override. PE files
220  // generally only contain the names of exported symbols.
221  return FNKind == FunctionNameKind::LinkageName && UseSymbolTable &&
222  isa<DWARFContext>(DebugInfoContext.get());
223 }
224 
226 SymbolizableObjectFile::symbolizeCode(object::SectionedAddress ModuleOffset,
227  FunctionNameKind FNKind,
228  bool UseSymbolTable) const {
229  DILineInfo LineInfo;
230  if (DebugInfoContext) {
231  LineInfo = DebugInfoContext->getLineInfoForAddress(
232  ModuleOffset, getDILineInfoSpecifier(FNKind));
233  }
234  // Override function name from symbol table if necessary.
235  if (shouldOverrideWithSymbolTable(FNKind, UseSymbolTable)) {
236  std::string FunctionName;
237  uint64_t Start, Size;
238  if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset.Address,
239  FunctionName, Start, Size)) {
240  LineInfo.FunctionName = FunctionName;
241  }
242  }
243  return LineInfo;
244 }
245 
246 DIInliningInfo SymbolizableObjectFile::symbolizeInlinedCode(
247  object::SectionedAddress ModuleOffset, FunctionNameKind FNKind,
248  bool UseSymbolTable) const {
249  DIInliningInfo InlinedContext;
250 
251  if (DebugInfoContext)
252  InlinedContext = DebugInfoContext->getInliningInfoForAddress(
253  ModuleOffset, getDILineInfoSpecifier(FNKind));
254  // Make sure there is at least one frame in context.
255  if (InlinedContext.getNumberOfFrames() == 0)
256  InlinedContext.addFrame(DILineInfo());
257 
258  // Override the function name in lower frame with name from symbol table.
259  if (shouldOverrideWithSymbolTable(FNKind, UseSymbolTable)) {
260  std::string FunctionName;
261  uint64_t Start, Size;
262  if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset.Address,
263  FunctionName, Start, Size)) {
264  InlinedContext.getMutableFrame(InlinedContext.getNumberOfFrames() - 1)
265  ->FunctionName = FunctionName;
266  }
267  }
268 
269  return InlinedContext;
270 }
271 
272 DIGlobal SymbolizableObjectFile::symbolizeData(
273  object::SectionedAddress ModuleOffset) const {
274  DIGlobal Res;
275  getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset.Address, Res.Name,
276  Res.Start, Res.Size);
277  return Res;
278 }
Represents either an error or a value T.
Definition: ErrorOr.h:56
bool isValidOffsetForAddress(uint32_t offset) const
Test the availability of enough bytes of data for a pointer from offset.
DILineInfo * getMutableFrame(unsigned Index)
Definition: DIContext.h:88
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Expected< StringRef > getName() const
Definition: ObjectFile.h:382
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
This class is the base class for all object file types.
Definition: ObjectFile.h:225
void addFrame(const DILineInfo &Frame)
Definition: DIContext.h:97
DINameKind
A DINameKind is passed to name search methods to specify a preference regarding the type of name reso...
Definition: DIContext.h:118
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
static DILineInfoSpecifier getDILineInfoSpecifier(FunctionNameKind FNKind)
A format-neutral container for source line information.
Definition: DIContext.h:30
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
The access may reference the value stored in memory.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
bool operator<(const SectionedAddress &LHS, const SectionedAddress &RHS)
Definition: ObjectFile.h:150
const ObjectFile * getObject() const
Definition: ObjectFile.h:410
bool empty() const
Definition: Module.h:607
uint64_t Start
Definition: DIContext.h:110
section_iterator_range sections() const
Definition: ObjectFile.h:315
uint32_t getNumberOfFrames() const
Definition: DIContext.h:93
Expected< section_iterator > getSection() const
Get section this symbol is defined in reference to.
Definition: ObjectFile.h:402
#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:1082
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:45
Controls which fields of DILineInfo container should be filled with data.
Definition: DIContext.h:122
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
A format-neutral container for inlined code description.
Definition: DIContext.h:77
uint64_t getAddress(uint32_t *offset_ptr) const
Extract an pointer from *offset_ptr.
DenseMap< SymbolStringPtr, JITEvaluatedSymbol > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
Definition: Core.h:47
Expected< uint64_t > getAddress() const
Returns the symbol virtual address (i.e.
Definition: ObjectFile.h:386
bool isLittleEndian() const
Definition: Binary.h:130
uint16_t getMachine() const
Definition: COFF.h:811
Expected< SymbolRef::Type > getType() const
Definition: ObjectFile.h:406
std::string Name
Definition: DIContext.h:109
std::string FunctionName
Definition: DIContext.h:32
virtual Triple::ArchType getArch() const =0
uint64_t Size
Definition: DIContext.h:111
std::vector< std::pair< SymbolRef, uint64_t > > computeSymbolSizes(const ObjectFile &O)
Definition: SymbolSize.cpp:40
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
iterator begin()
Definition: DenseMap.h:99
#define I(x, y, z)
Definition: MD5.cpp:58
iterator_range< export_directory_iterator > export_directories() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:322
uint32_t Size
Definition: Profile.cpp:46
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:122
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition: Error.cpp:93
Container for description of a global variable.
Definition: DIContext.h:108