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 "llvm/DebugInfo/Symbolize/SymbolizableObjectFile.h"
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/BinaryFormat/COFF.h"
16#include "llvm/DebugInfo/DWARF/DWARFContext.h"
17#include "llvm/Object/COFF.h"
18#include "llvm/Object/ELFObjectFile.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 "llvm/TargetParser/Triple.h"
24
25using namespace llvm;
26using namespace object;
27using namespace symbolize;
28
29Expected<std::unique_ptr<SymbolizableObjectFile>>
30SymbolizableObjectFile::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(p: new DataExtractor(*E, Obj->isLittleEndian()));
51 OpdAddress = Section->getAddress();
52 break;
53 }
54 }
55 }
56 std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
57 computeSymbolSizes(O: *Obj);
58 for (auto &P : Symbols)
59 if (Error E =
60 res->addSymbol(Symbol: P.first, SymbolSize: P.second, OpdExtractor: OpdExtractor.get(), OpdAddress))
61 return std::move(E);
62
63 // If this is a COFF object and we didn't find any symbols, try the export
64 // table.
65 if (Symbols.empty()) {
66 if (auto *CoffObj = dyn_cast<COFFObjectFile>(Val: Obj))
67 if (Error E = res->addCoffExportSymbols(CoffObj))
68 return std::move(E);
69 }
70
71 std::vector<SymbolDesc> &SS = res->Symbols;
72 // Sort by (Addr,Size,Name). If several SymbolDescs share the same Addr,
73 // pick the one with the largest Size. This helps us avoid symbols with no
74 // size information (Size=0).
75 llvm::stable_sort(Range&: SS);
76 auto I = SS.begin(), E = SS.end(), J = SS.begin();
77 while (I != E) {
78 auto OI = I;
79 while (++I != E && OI->Addr == I->Addr) {
80 }
81 *J++ = I[-1];
82 }
83 SS.erase(first: J, last: SS.end());
84
85 return std::move(res);
86}
87
88SymbolizableObjectFile::SymbolizableObjectFile(const ObjectFile *Obj,
89 std::unique_ptr<DIContext> DICtx,
90 bool UntagAddresses)
91 : Module(Obj), DebugInfoContext(std::move(DICtx)),
92 UntagAddresses(UntagAddresses) {}
93
94namespace {
95
96struct OffsetNamePair {
97 uint32_t Offset;
98 StringRef Name;
99
100 bool operator<(const OffsetNamePair &R) const {
101 return Offset < R.Offset;
102 }
103};
104
105} // end anonymous namespace
106
107Error SymbolizableObjectFile::addCoffExportSymbols(
108 const COFFObjectFile *CoffObj) {
109 // Get all export names and offsets.
110 std::vector<OffsetNamePair> ExportSyms;
111 for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {
112 StringRef Name;
113 uint32_t Offset;
114 if (auto EC = Ref.getSymbolName(Result&: Name))
115 return EC;
116 if (auto EC = Ref.getExportRVA(Result&: Offset))
117 return EC;
118 ExportSyms.push_back(x: OffsetNamePair{.Offset: Offset, .Name: Name});
119 }
120 if (ExportSyms.empty())
121 return Error::success();
122
123 // Sort by ascending offset.
124 array_pod_sort(Start: ExportSyms.begin(), End: ExportSyms.end());
125
126 // Approximate the symbol sizes by assuming they run to the next symbol.
127 // FIXME: This assumes all exports are functions.
128 uint64_t ImageBase = CoffObj->getImageBase();
129 for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {
130 OffsetNamePair &Export = *I;
131 // FIXME: The last export has a one byte size now.
132 uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;
133 uint64_t SymbolStart = ImageBase + Export.Offset;
134 uint64_t SymbolSize = NextOffset - Export.Offset;
135 Symbols.push_back(x: {.Addr: SymbolStart, .Size: SymbolSize, .Name: Export.Name, .ELFLocalSymIdx: 0});
136 }
137 return Error::success();
138}
139
140Error SymbolizableObjectFile::addSymbol(const SymbolRef &Symbol,
141 uint64_t SymbolSize,
142 DataExtractor *OpdExtractor,
143 uint64_t OpdAddress) {
144 // Avoid adding symbols from an unknown/undefined section.
145 const ObjectFile &Obj = *Symbol.getObject();
146 Expected<StringRef> SymbolNameOrErr = Symbol.getName();
147 if (!SymbolNameOrErr)
148 return SymbolNameOrErr.takeError();
149 StringRef SymbolName = *SymbolNameOrErr;
150
151 uint32_t ELFSymIdx =
152 Obj.isELF() ? ELFSymbolRef(Symbol).getRawDataRefImpl().d.b : 0;
153 Expected<section_iterator> Sec = Symbol.getSection();
154 if (!Sec || Obj.section_end() == *Sec) {
155 if (Obj.isELF()) {
156 // Store the (index, filename) pair for a file symbol.
157 ELFSymbolRef ESym(Symbol);
158 if (ESym.getELFType() == ELF::STT_FILE)
159 FileSymbols.emplace_back(args&: ELFSymIdx, args&: SymbolName);
160 }
161 return Error::success();
162 }
163
164 Expected<SymbolRef::Type> SymbolTypeOrErr = Symbol.getType();
165 if (!SymbolTypeOrErr)
166 return SymbolTypeOrErr.takeError();
167 SymbolRef::Type SymbolType = *SymbolTypeOrErr;
168 if (Obj.isELF()) {
169 // Ignore any symbols coming from sections that don't have runtime
170 // allocated memory.
171 if ((elf_section_iterator(*Sec)->getFlags() & ELF::SHF_ALLOC) == 0)
172 return Error::success();
173
174 // Allow function and data symbols. Additionally allow STT_NONE, which are
175 // common for functions defined in assembly.
176 uint8_t Type = ELFSymbolRef(Symbol).getELFType();
177 if (Type != ELF::STT_NOTYPE && Type != ELF::STT_FUNC &&
178 Type != ELF::STT_OBJECT && Type != ELF::STT_GNU_IFUNC)
179 return Error::success();
180 // Some STT_NOTYPE symbols are not desired. This excludes STT_SECTION and
181 // ARM mapping symbols.
182 uint32_t Flags = cantFail(ValOrErr: Symbol.getFlags());
183 if (Flags & SymbolRef::SF_FormatSpecific)
184 return Error::success();
185 } else if (SymbolType != SymbolRef::ST_Function &&
186 SymbolType != SymbolRef::ST_Data) {
187 return Error::success();
188 }
189
190 Expected<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
191 if (!SymbolAddressOrErr)
192 return SymbolAddressOrErr.takeError();
193 uint64_t SymbolAddress = *SymbolAddressOrErr;
194 if (UntagAddresses) {
195 // For kernel addresses, bits 56-63 need to be set, so we sign extend bit 55
196 // into bits 56-63 instead of masking them out.
197 SymbolAddress &= (1ull << 56) - 1;
198 SymbolAddress = (int64_t(SymbolAddress) << 8) >> 8;
199 }
200 if (OpdExtractor) {
201 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
202 // function descriptors. The first word of the descriptor is a pointer to
203 // the function's code.
204 // For the purposes of symbolization, pretend the symbol's address is that
205 // of the function's code, not the descriptor.
206 uint64_t OpdOffset = SymbolAddress - OpdAddress;
207 unsigned AddressSize = Obj.getBytesInAddress();
208 if (OpdExtractor->isValidOffsetForDataOfSize(offset: OpdOffset, length: AddressSize))
209 SymbolAddress = OpdExtractor->getUnsigned(offset_ptr: &OpdOffset, byte_size: AddressSize);
210 }
211 // Mach-O symbol table names have leading underscore, skip it.
212 if (Module->isMachO())
213 SymbolName.consume_front(Prefix: "_");
214
215 if (Obj.isELF() && ELFSymbolRef(Symbol).getBinding() != ELF::STB_LOCAL)
216 ELFSymIdx = 0;
217 Symbols.push_back(x: {.Addr: SymbolAddress, .Size: SymbolSize, .Name: SymbolName, .ELFLocalSymIdx: ELFSymIdx});
218 return Error::success();
219}
220
221// Return true if this is a 32-bit x86 PE COFF module.
222bool SymbolizableObjectFile::isWin32Module() const {
223 auto *CoffObject = dyn_cast<COFFObjectFile>(Val: Module);
224 return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
225}
226
227uint64_t SymbolizableObjectFile::getModulePreferredBase() const {
228 if (auto *CoffObject = dyn_cast<COFFObjectFile>(Val: Module))
229 return CoffObject->getImageBase();
230 return 0;
231}
232
233bool SymbolizableObjectFile::getNameFromSymbolTable(
234 uint64_t Address, std::string &Name, uint64_t &Addr, uint64_t &Size,
235 std::string &FileName) const {
236 SymbolDesc SD{.Addr: Address, UINT64_C(-1), .Name: StringRef(), .ELFLocalSymIdx: 0};
237 auto SymbolIterator = llvm::upper_bound(Range: Symbols, Value&: SD);
238 if (SymbolIterator == Symbols.begin())
239 return false;
240 --SymbolIterator;
241 if (SymbolIterator->Size != 0 &&
242 SymbolIterator->Addr + SymbolIterator->Size <= Address)
243 return false;
244 Name = SymbolIterator->Name.str();
245 Addr = SymbolIterator->Addr;
246 Size = SymbolIterator->Size;
247
248 if (SymbolIterator->ELFLocalSymIdx != 0) {
249 // If this is an ELF local symbol, find the STT_FILE symbol preceding
250 // SymbolIterator to get the filename. The ELF spec requires the STT_FILE
251 // symbol (if present) precedes the other STB_LOCAL symbols for the file.
252 assert(Module->isELF());
253 auto It = llvm::upper_bound(
254 Range: FileSymbols,
255 Value: std::make_pair(x: SymbolIterator->ELFLocalSymIdx, y: StringRef()));
256 if (It != FileSymbols.begin())
257 FileName = It[-1].second.str();
258 }
259 return true;
260}
261
262bool SymbolizableObjectFile::shouldOverrideWithSymbolTable(
263 FunctionNameKind FNKind, bool UseSymbolTable) const {
264 // When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives
265 // better answers for linkage names than the DIContext. Otherwise, we are
266 // probably using PEs and PDBs, and we shouldn't do the override. PE files
267 // generally only contain the names of exported symbols.
268 return FNKind == FunctionNameKind::LinkageName && UseSymbolTable &&
269 isa<DWARFContext>(Val: DebugInfoContext.get());
270}
271
272object::SectionedAddress SymbolizableObjectFile::convertDwarfOffsetForWasm(
273 object::SectionedAddress ModuleOffset) const {
274 if (!Module->isWasm())
275 return ModuleOffset;
276
277 // For Wasm object files, addresses are already section-relative.
278 if (Module->isRelocatableObject())
279 return ModuleOffset;
280
281 // We are dealing with a linked Wasm file, which uses file offsets.
282 for (const SectionRef &Sec : Module->sections()) {
283 if (Sec.getIndex() == ModuleOffset.SectionIndex) {
284 if (Sec.isText()) {
285 ModuleOffset.Address -= Sec.getAddress();
286 return ModuleOffset;
287 }
288 break;
289 }
290 }
291
292 // If the address is not in a text section, or we couldn't find a
293 // matching section, invalidate it. This prevents it from incorrectly
294 // being interpreted as as section-relative DWARF offset.
295 ModuleOffset.Address = UINT64_MAX;
296 return ModuleOffset;
297}
298
299DILineInfo
300SymbolizableObjectFile::symbolizeCode(object::SectionedAddress ModuleOffset,
301 DILineInfoSpecifier LineInfoSpecifier,
302 bool UseSymbolTable) const {
303 if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
304 ModuleOffset.SectionIndex =
305 getModuleSectionIndexForAddress(Address: ModuleOffset.Address);
306 DILineInfo LineInfo;
307 object::SectionedAddress DWARFOffset =
308 convertDwarfOffsetForWasm(ModuleOffset);
309 std::optional<DILineInfo> DBGLineInfo =
310 DebugInfoContext->getLineInfoForAddress(Address: DWARFOffset, Specifier: LineInfoSpecifier);
311 if (DBGLineInfo)
312 LineInfo = *DBGLineInfo;
313
314 // Override function name from symbol table if necessary.
315 if (shouldOverrideWithSymbolTable(FNKind: LineInfoSpecifier.FNKind, UseSymbolTable)) {
316 std::string FunctionName, FileName;
317 uint64_t Start, Size;
318 if (getNameFromSymbolTable(Address: ModuleOffset.Address, Name&: FunctionName, Addr&: Start, Size,
319 FileName)) {
320 LineInfo.FunctionName = FunctionName;
321 LineInfo.StartAddress = Start;
322 // Only use the filename from symbol table if the debug info for the
323 // address is missing.
324 if (!DBGLineInfo && !FileName.empty())
325 LineInfo.FileName = FileName;
326 }
327 }
328 return LineInfo;
329}
330
331DIInliningInfo SymbolizableObjectFile::symbolizeInlinedCode(
332 object::SectionedAddress ModuleOffset,
333 DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const {
334 if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
335 ModuleOffset.SectionIndex =
336 getModuleSectionIndexForAddress(Address: ModuleOffset.Address);
337 object::SectionedAddress DWARFOffset =
338 convertDwarfOffsetForWasm(ModuleOffset);
339 DIInliningInfo InlinedContext = DebugInfoContext->getInliningInfoForAddress(
340 Address: DWARFOffset, Specifier: LineInfoSpecifier);
341
342 // Make sure there is at least one frame in context.
343 bool EmptyFrameAdded = false;
344 if (InlinedContext.getNumberOfFrames() == 0) {
345 EmptyFrameAdded = true;
346 InlinedContext.addFrame(Frame: DILineInfo());
347 }
348
349 // Override the function name in lower frame with name from symbol table.
350 if (shouldOverrideWithSymbolTable(FNKind: LineInfoSpecifier.FNKind, UseSymbolTable)) {
351 std::string FunctionName, FileName;
352 uint64_t Start, Size;
353 if (getNameFromSymbolTable(Address: ModuleOffset.Address, Name&: FunctionName, Addr&: Start, Size,
354 FileName)) {
355 DILineInfo *LI = InlinedContext.getMutableFrame(
356 Index: InlinedContext.getNumberOfFrames() - 1);
357 LI->FunctionName = FunctionName;
358 LI->StartAddress = Start;
359 // Only use the filename from symbol table if the debug info for the
360 // address is missing.
361 if (EmptyFrameAdded && !FileName.empty())
362 LI->FileName = FileName;
363 }
364 }
365
366 return InlinedContext;
367}
368
369DIGlobal SymbolizableObjectFile::symbolizeData(
370 object::SectionedAddress ModuleOffset) const {
371 DIGlobal Res;
372 std::string FileName;
373 getNameFromSymbolTable(Address: ModuleOffset.Address, Name&: Res.Name, Addr&: Res.Start, Size&: Res.Size,
374 FileName);
375 Res.DeclFile = FileName;
376
377 // Try and get a better filename:lineno pair from the debuginfo, if present.
378 std::optional<DILineInfo> DL =
379 DebugInfoContext->getLineInfoForDataAddress(Address: ModuleOffset);
380 if (DL && DL->Line != 0) {
381 Res.DeclFile = DL->FileName;
382 Res.DeclLine = DL->Line;
383 }
384 return Res;
385}
386
387std::vector<DILocal> SymbolizableObjectFile::symbolizeFrame(
388 object::SectionedAddress ModuleOffset) const {
389 if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
390 ModuleOffset.SectionIndex =
391 getModuleSectionIndexForAddress(Address: ModuleOffset.Address);
392 object::SectionedAddress DWARFOffset =
393 convertDwarfOffsetForWasm(ModuleOffset);
394 return DebugInfoContext->getLocalsForAddress(Address: DWARFOffset);
395}
396
397std::vector<object::SectionedAddress>
398SymbolizableObjectFile::findSymbol(StringRef Symbol, uint64_t Offset) const {
399 std::vector<object::SectionedAddress> Result;
400 for (const SymbolDesc &Sym : Symbols) {
401 if (Sym.Name == Symbol) {
402 uint64_t Addr = Sym.Addr;
403 if (Offset < Sym.Size)
404 Addr += Offset;
405 object::SectionedAddress A{.Address: Addr, .SectionIndex: getModuleSectionIndexForAddress(Address: Addr)};
406 Result.push_back(x: A);
407 }
408 }
409 return Result;
410}
411
412/// Search for the first occurence of specified Address in ObjectFile.
413uint64_t SymbolizableObjectFile::getModuleSectionIndexForAddress(
414 uint64_t Address) const {
415
416 for (SectionRef Sec : Module->sections()) {
417 if (!Sec.isText() || Sec.isVirtual())
418 continue;
419
420 if (Address >= Sec.getAddress() &&
421 Address < Sec.getAddress() + Sec.getSize())
422 return Sec.getIndex();
423 }
424
425 return object::SectionedAddress::UndefSection;
426}
427