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 = (int64_t(SymbolAddress) << 8) >> 8;
182   }
183   if (OpdExtractor) {
184     // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
185     // function descriptors. The first word of the descriptor is a pointer to
186     // the function's code.
187     // For the purposes of symbolization, pretend the symbol's address is that
188     // of the function's code, not the descriptor.
189     uint64_t OpdOffset = SymbolAddress - OpdAddress;
190     uint32_t OpdOffset32 = OpdOffset;
191     if (OpdOffset == OpdOffset32 &&
192         OpdExtractor->isValidOffsetForAddress(OpdOffset32))
193       SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
194   }
195   Expected<StringRef> SymbolNameOrErr = Symbol.getName();
196   if (!SymbolNameOrErr)
197     return errorToErrorCode(SymbolNameOrErr.takeError());
198   StringRef SymbolName = *SymbolNameOrErr;
199   // Mach-O symbol table names have leading underscore, skip it.
200   if (Module->isMachO() && !SymbolName.empty() && SymbolName[0] == '_')
201     SymbolName = SymbolName.drop_front();
202   // FIXME: If a function has alias, there are two entries in symbol table
203   // with same address size. Make sure we choose the correct one.
204   auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
205   SymbolDesc SD = { SymbolAddress, SymbolSize };
206   M.emplace_back(SD, SymbolName);
207   return std::error_code();
208 }
209 
210 // Return true if this is a 32-bit x86 PE COFF module.
211 bool SymbolizableObjectFile::isWin32Module() const {
212   auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
213   return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
214 }
215 
216 uint64_t SymbolizableObjectFile::getModulePreferredBase() const {
217   if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
218     return CoffObject->getImageBase();
219   return 0;
220 }
221 
222 bool SymbolizableObjectFile::getNameFromSymbolTable(SymbolRef::Type Type,
223                                                     uint64_t Address,
224                                                     std::string &Name,
225                                                     uint64_t &Addr,
226                                                     uint64_t &Size) const {
227   const auto &Symbols = Type == SymbolRef::ST_Function ? Functions : Objects;
228   std::pair<SymbolDesc, StringRef> SD{{Address, UINT64_C(-1)}, StringRef()};
229   auto SymbolIterator = llvm::upper_bound(Symbols, SD);
230   if (SymbolIterator == Symbols.begin())
231     return false;
232   --SymbolIterator;
233   if (SymbolIterator->first.Size != 0 &&
234       SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
235     return false;
236   Name = SymbolIterator->second.str();
237   Addr = SymbolIterator->first.Addr;
238   Size = SymbolIterator->first.Size;
239   return true;
240 }
241 
242 bool SymbolizableObjectFile::shouldOverrideWithSymbolTable(
243     FunctionNameKind FNKind, bool UseSymbolTable) const {
244   // When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives
245   // better answers for linkage names than the DIContext. Otherwise, we are
246   // probably using PEs and PDBs, and we shouldn't do the override. PE files
247   // generally only contain the names of exported symbols.
248   return FNKind == FunctionNameKind::LinkageName && UseSymbolTable &&
249          isa<DWARFContext>(DebugInfoContext.get());
250 }
251 
252 DILineInfo
253 SymbolizableObjectFile::symbolizeCode(object::SectionedAddress ModuleOffset,
254                                       FunctionNameKind FNKind,
255                                       bool UseSymbolTable) const {
256   if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
257     ModuleOffset.SectionIndex =
258         getModuleSectionIndexForAddress(ModuleOffset.Address);
259   DILineInfo LineInfo = DebugInfoContext->getLineInfoForAddress(
260       ModuleOffset, getDILineInfoSpecifier(FNKind));
261 
262   // Override function name from symbol table if necessary.
263   if (shouldOverrideWithSymbolTable(FNKind, UseSymbolTable)) {
264     std::string FunctionName;
265     uint64_t Start, Size;
266     if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset.Address,
267                                FunctionName, Start, Size)) {
268       LineInfo.FunctionName = FunctionName;
269     }
270   }
271   return LineInfo;
272 }
273 
274 DIInliningInfo SymbolizableObjectFile::symbolizeInlinedCode(
275     object::SectionedAddress ModuleOffset, FunctionNameKind FNKind,
276     bool UseSymbolTable) const {
277   if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
278     ModuleOffset.SectionIndex =
279         getModuleSectionIndexForAddress(ModuleOffset.Address);
280   DIInliningInfo InlinedContext = DebugInfoContext->getInliningInfoForAddress(
281       ModuleOffset, getDILineInfoSpecifier(FNKind));
282 
283   // Make sure there is at least one frame in context.
284   if (InlinedContext.getNumberOfFrames() == 0)
285     InlinedContext.addFrame(DILineInfo());
286 
287   // Override the function name in lower frame with name from symbol table.
288   if (shouldOverrideWithSymbolTable(FNKind, UseSymbolTable)) {
289     std::string FunctionName;
290     uint64_t Start, Size;
291     if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset.Address,
292                                FunctionName, Start, Size)) {
293       InlinedContext.getMutableFrame(InlinedContext.getNumberOfFrames() - 1)
294           ->FunctionName = FunctionName;
295     }
296   }
297 
298   return InlinedContext;
299 }
300 
301 DIGlobal SymbolizableObjectFile::symbolizeData(
302     object::SectionedAddress ModuleOffset) const {
303   DIGlobal Res;
304   getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset.Address, Res.Name,
305                          Res.Start, Res.Size);
306   return Res;
307 }
308 
309 std::vector<DILocal> SymbolizableObjectFile::symbolizeFrame(
310     object::SectionedAddress ModuleOffset) const {
311   if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
312     ModuleOffset.SectionIndex =
313         getModuleSectionIndexForAddress(ModuleOffset.Address);
314   return DebugInfoContext->getLocalsForAddress(ModuleOffset);
315 }
316 
317 /// Search for the first occurence of specified Address in ObjectFile.
318 uint64_t SymbolizableObjectFile::getModuleSectionIndexForAddress(
319     uint64_t Address) const {
320 
321   for (SectionRef Sec : Module->sections()) {
322     if (!Sec.isText() || Sec.isVirtual())
323       continue;
324 
325     if (Address >= Sec.getAddress() &&
326         Address < Sec.getAddress() + Sec.getSize())
327       return Sec.getIndex();
328   }
329 
330   return object::SectionedAddress::UndefSection;
331 }
332