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"
18#include "llvm/DebugInfo/DWARF/DWARFContext.h"
19#include "llvm/DebugInfo/Symbolize/SymbolizableModule.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"
24#include "llvm/Support/DataExtractor.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
34using namespace llvm;
35using namespace object;
36using namespace symbolize;
37
38Expected<std::unique_ptr<SymbolizableObjectFile>>
39SymbolizableObjectFile::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
103SymbolizableObjectFile::SymbolizableObjectFile(const ObjectFile *Obj,
104                                               std::unique_ptr<DIContext> DICtx,
105                                               bool UntagAddresses)
106    : Module(Obj), DebugInfoContext(std::move(DICtx)),
107      UntagAddresses(UntagAddresses) {}
108
109namespace {
110
111struct OffsetNamePair {
112  uint32_t Offset;
113  StringRef Name;
114
115  bool operator<(const OffsetNamePair &R) const {
116    return Offset < R.Offset;
117  }
118};
119
120} // end anonymous namespace
121
122Error 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;
128    uint32_t Offset;
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
156Error 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.
207bool SymbolizableObjectFile::isWin32Module() const {
208  auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
209  return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
210}
211
212uint64_t SymbolizableObjectFile::getModulePreferredBase() const {
213  if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
214    return CoffObject->getImageBase();
215  return 0;
216}
217
218bool 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
238bool 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
248DILineInfo
249SymbolizableObjectFile::symbolizeCode(object::SectionedAddress ModuleOffset,
250                                      DILineInfoSpecifier LineInfoSpecifier,
251                                      bool UseSymbolTable) const {
252  if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
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
270DIInliningInfo SymbolizableObjectFile::symbolizeInlinedCode(
271    object::SectionedAddress ModuleOffset,
272    DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const {
273  if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
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
297DIGlobal 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
305std::vector<DILocal> SymbolizableObjectFile::symbolizeFrame(
306    object::SectionedAddress ModuleOffset) const {
307  if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
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.
314uint64_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
326  return object::SectionedAddress::UndefSection;
327}
328