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