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