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