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()) {
56  if (auto EC = Section->getName(Name))
57  return EC;
58  if (Name == ".opd") {
59  Expected<StringRef> E = Section->getContents();
60  if (!E)
61  return errorToErrorCode(E.takeError());
62  OpdExtractor.reset(new DataExtractor(*E, 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 
82  std::vector<std::pair<SymbolDesc, StringRef>> &Fs = res->Functions,
83  &Os = res->Objects;
84  auto Uniquify = [](std::vector<std::pair<SymbolDesc, StringRef>> &S) {
85  // Sort by (Addr,Size,Name). If several SymbolDescs share the same Addr,
86  // pick the one with the largest Size. This helps us avoid symbols with no
87  // size information (Size=0).
88  llvm::sort(S);
89  auto I = S.begin(), E = S.end(), J = S.begin();
90  while (I != E) {
91  auto OI = I;
92  while (++I != E && OI->first.Addr == I->first.Addr) {
93  }
94  *J++ = I[-1];
95  }
96  S.erase(J, S.end());
97  };
98  Uniquify(Fs);
99  Uniquify(Os);
100 
101  return std::move(res);
102 }
103 
104 SymbolizableObjectFile::SymbolizableObjectFile(ObjectFile *Obj,
105  std::unique_ptr<DIContext> DICtx)
106  : Module(Obj), DebugInfoContext(std::move(DICtx)) {}
107 
108 namespace {
109 
110 struct OffsetNamePair {
112  StringRef Name;
113 
114  bool operator<(const OffsetNamePair &R) const {
115  return Offset < R.Offset;
116  }
117 };
118 
119 } // end anonymous namespace
120 
121 std::error_code SymbolizableObjectFile::addCoffExportSymbols(
122  const COFFObjectFile *CoffObj) {
123  // Get all export names and offsets.
124  std::vector<OffsetNamePair> ExportSyms;
125  for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {
126  StringRef Name;
128  if (auto EC = Ref.getSymbolName(Name))
129  return EC;
130  if (auto EC = Ref.getExportRVA(Offset))
131  return EC;
132  ExportSyms.push_back(OffsetNamePair{Offset, Name});
133  }
134  if (ExportSyms.empty())
135  return std::error_code();
136 
137  // Sort by ascending offset.
138  array_pod_sort(ExportSyms.begin(), ExportSyms.end());
139 
140  // Approximate the symbol sizes by assuming they run to the next symbol.
141  // FIXME: This assumes all exports are functions.
142  uint64_t ImageBase = CoffObj->getImageBase();
143  for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {
144  OffsetNamePair &Export = *I;
145  // FIXME: The last export has a one byte size now.
146  uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;
147  uint64_t SymbolStart = ImageBase + Export.Offset;
148  uint64_t SymbolSize = NextOffset - Export.Offset;
149  SymbolDesc SD = {SymbolStart, SymbolSize};
150  Functions.emplace_back(SD, Export.Name);
151  }
152  return std::error_code();
153 }
154 
155 std::error_code SymbolizableObjectFile::addSymbol(const SymbolRef &Symbol,
156  uint64_t SymbolSize,
157  DataExtractor *OpdExtractor,
158  uint64_t OpdAddress) {
159  // Avoid adding symbols from an unknown/undefined section.
160  const ObjectFile *Obj = Symbol.getObject();
161  Expected<section_iterator> Sec = Symbol.getSection();
162  if (!Sec || (Obj && Obj->section_end() == *Sec))
163  return std::error_code();
164  Expected<SymbolRef::Type> SymbolTypeOrErr = Symbol.getType();
165  if (!SymbolTypeOrErr)
166  return errorToErrorCode(SymbolTypeOrErr.takeError());
167  SymbolRef::Type SymbolType = *SymbolTypeOrErr;
168  if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
169  return std::error_code();
170  Expected<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
171  if (!SymbolAddressOrErr)
172  return errorToErrorCode(SymbolAddressOrErr.takeError());
173  uint64_t SymbolAddress = *SymbolAddressOrErr;
174  if (OpdExtractor) {
175  // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
176  // function descriptors. The first word of the descriptor is a pointer to
177  // the function's code.
178  // For the purposes of symbolization, pretend the symbol's address is that
179  // of the function's code, not the descriptor.
180  uint64_t OpdOffset = SymbolAddress - OpdAddress;
181  uint32_t OpdOffset32 = OpdOffset;
182  if (OpdOffset == OpdOffset32 &&
183  OpdExtractor->isValidOffsetForAddress(OpdOffset32))
184  SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
185  }
186  Expected<StringRef> SymbolNameOrErr = Symbol.getName();
187  if (!SymbolNameOrErr)
188  return errorToErrorCode(SymbolNameOrErr.takeError());
189  StringRef SymbolName = *SymbolNameOrErr;
190  // Mach-O symbol table names have leading underscore, skip it.
191  if (Module->isMachO() && !SymbolName.empty() && SymbolName[0] == '_')
192  SymbolName = SymbolName.drop_front();
193  // FIXME: If a function has alias, there are two entries in symbol table
194  // with same address size. Make sure we choose the correct one.
195  auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
196  SymbolDesc SD = { SymbolAddress, SymbolSize };
197  M.emplace_back(SD, SymbolName);
198  return std::error_code();
199 }
200 
201 // Return true if this is a 32-bit x86 PE COFF module.
202 bool SymbolizableObjectFile::isWin32Module() const {
203  auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
204  return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
205 }
206 
207 uint64_t SymbolizableObjectFile::getModulePreferredBase() const {
208  if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
209  return CoffObject->getImageBase();
210  return 0;
211 }
212 
213 bool SymbolizableObjectFile::getNameFromSymbolTable(SymbolRef::Type Type,
214  uint64_t Address,
215  std::string &Name,
216  uint64_t &Addr,
217  uint64_t &Size) const {
218  const auto &Symbols = Type == SymbolRef::ST_Function ? Functions : Objects;
219  std::pair<SymbolDesc, StringRef> SD{{Address, UINT64_C(-1)}, StringRef()};
220  auto SymbolIterator = llvm::upper_bound(Symbols, SD);
221  if (SymbolIterator == Symbols.begin())
222  return false;
223  --SymbolIterator;
224  if (SymbolIterator->first.Size != 0 &&
225  SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
226  return false;
227  Name = SymbolIterator->second.str();
228  Addr = SymbolIterator->first.Addr;
229  Size = SymbolIterator->first.Size;
230  return true;
231 }
232 
233 bool SymbolizableObjectFile::shouldOverrideWithSymbolTable(
234  FunctionNameKind FNKind, bool UseSymbolTable) const {
235  // When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives
236  // better answers for linkage names than the DIContext. Otherwise, we are
237  // probably using PEs and PDBs, and we shouldn't do the override. PE files
238  // generally only contain the names of exported symbols.
239  return FNKind == FunctionNameKind::LinkageName && UseSymbolTable &&
240  isa<DWARFContext>(DebugInfoContext.get());
241 }
242 
244 SymbolizableObjectFile::symbolizeCode(object::SectionedAddress ModuleOffset,
245  FunctionNameKind FNKind,
246  bool UseSymbolTable) const {
247  DILineInfo LineInfo;
248 
250  ModuleOffset.SectionIndex =
251  getModuleSectionIndexForAddress(ModuleOffset.Address);
252 
253  if (DebugInfoContext) {
254  LineInfo = DebugInfoContext->getLineInfoForAddress(
255  ModuleOffset, getDILineInfoSpecifier(FNKind));
256  }
257  // Override function name from symbol table if necessary.
258  if (shouldOverrideWithSymbolTable(FNKind, UseSymbolTable)) {
259  std::string FunctionName;
260  uint64_t Start, Size;
261  if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset.Address,
262  FunctionName, Start, Size)) {
263  LineInfo.FunctionName = FunctionName;
264  }
265  }
266  return LineInfo;
267 }
268 
269 DIInliningInfo SymbolizableObjectFile::symbolizeInlinedCode(
270  object::SectionedAddress ModuleOffset, FunctionNameKind FNKind,
271  bool UseSymbolTable) const {
272  DIInliningInfo InlinedContext;
273 
275  ModuleOffset.SectionIndex =
276  getModuleSectionIndexForAddress(ModuleOffset.Address);
277 
278  if (DebugInfoContext)
279  InlinedContext = DebugInfoContext->getInliningInfoForAddress(
280  ModuleOffset, getDILineInfoSpecifier(FNKind));
281  // Make sure there is at least one frame in context.
282  if (InlinedContext.getNumberOfFrames() == 0)
283  InlinedContext.addFrame(DILineInfo());
284 
285  // Override the function name in lower frame with name from symbol table.
286  if (shouldOverrideWithSymbolTable(FNKind, UseSymbolTable)) {
287  std::string FunctionName;
288  uint64_t Start, Size;
289  if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset.Address,
290  FunctionName, Start, Size)) {
291  InlinedContext.getMutableFrame(InlinedContext.getNumberOfFrames() - 1)
292  ->FunctionName = FunctionName;
293  }
294  }
295 
296  return InlinedContext;
297 }
298 
299 DIGlobal SymbolizableObjectFile::symbolizeData(
300  object::SectionedAddress ModuleOffset) const {
301  DIGlobal Res;
302  getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset.Address, Res.Name,
303  Res.Start, Res.Size);
304  return Res;
305 }
306 
307 /// Search for the first occurence of specified Address in ObjectFile.
308 uint64_t SymbolizableObjectFile::getModuleSectionIndexForAddress(
309  uint64_t Address) const {
310 
311  for (SectionRef Sec : Module->sections()) {
312  if (!Sec.isText() || Sec.isVirtual())
313  continue;
314 
315  if (Address >= Sec.getAddress() &&
316  Address < Sec.getAddress() + Sec.getSize())
317  return Sec.getIndex();
318  }
319 
321 }
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:380
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
static const uint64_t UndefSection
Definition: ObjectFile.h:145
This class is the base class for all object file types.
Definition: ObjectFile.h:226
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:151
const ObjectFile * getObject() const
Definition: ObjectFile.h:408
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:400
#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.
Expected< uint64_t > getAddress() const
Returns the symbol virtual address (i.e.
Definition: ObjectFile.h:384
bool isLittleEndian() const
Definition: Binary.h:138
uint16_t getMachine() const
Definition: COFF.h:811
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1115
Expected< SymbolRef::Type > getType() const
Definition: ObjectFile.h:404
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:165
virtual section_iterator section_end() const =0
#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:332
uint32_t Size
Definition: Profile.cpp:46
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
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81
auto upper_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1296