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