1 //===-- LLVMSymbolize.cpp -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation for LLVM symbolization library.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMSymbolize.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Config/config.h"
17 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
18 #include "llvm/DebugInfo/PDB/PDB.h"
19 #include "llvm/DebugInfo/PDB/PDBContext.h"
20 #include "llvm/Object/ELFObjectFile.h"
21 #include "llvm/Object/MachO.h"
22 #include "llvm/Object/SymbolSize.h"
23 #include "llvm/Support/COFF.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Compression.h"
26 #include "llvm/Support/DataExtractor.h"
27 #include "llvm/Support/Errc.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
37 #pragma comment(lib, "dbghelp.lib")
39 // Windows.h conflicts with our COFF header definitions.
40 #ifdef IMAGE_FILE_MACHINE_I386
41 #undef IMAGE_FILE_MACHINE_I386
48 static bool error(std::error_code ec) {
51 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
55 static DILineInfoSpecifier
56 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
57 return DILineInfoSpecifier(
58 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
62 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
63 : Module(Obj), DebugInfoContext(DICtx) {
64 std::unique_ptr<DataExtractor> OpdExtractor;
65 uint64_t OpdAddress = 0;
66 // Find the .opd (function descriptor) section if any, for big-endian
68 if (Module->getArch() == Triple::ppc64) {
69 for (section_iterator Section : Module->sections()) {
71 if (!error(Section->getName(Name)) && Name == ".opd") {
73 if (!error(Section->getContents(Data))) {
74 OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
75 Module->getBytesInAddress()));
76 OpdAddress = Section->getAddress();
82 std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
83 computeSymbolSizes(*Module);
84 for (auto &P : Symbols)
85 addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress);
88 void ModuleInfo::addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
89 DataExtractor *OpdExtractor, uint64_t OpdAddress) {
90 SymbolRef::Type SymbolType = Symbol.getType();
91 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
93 ErrorOr<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
94 if (error(SymbolAddressOrErr.getError()))
96 uint64_t SymbolAddress = *SymbolAddressOrErr;
98 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
99 // function descriptors. The first word of the descriptor is a pointer to
100 // the function's code.
101 // For the purposes of symbolization, pretend the symbol's address is that
102 // of the function's code, not the descriptor.
103 uint64_t OpdOffset = SymbolAddress - OpdAddress;
104 uint32_t OpdOffset32 = OpdOffset;
105 if (OpdOffset == OpdOffset32 &&
106 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
107 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
109 ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName();
110 if (error(SymbolNameOrErr.getError()))
112 StringRef SymbolName = *SymbolNameOrErr;
113 // Mach-O symbol table names have leading underscore, skip it.
114 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
115 SymbolName = SymbolName.drop_front();
116 // FIXME: If a function has alias, there are two entries in symbol table
117 // with same address size. Make sure we choose the correct one.
118 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
119 SymbolDesc SD = { SymbolAddress, SymbolSize };
120 M.insert(std::make_pair(SD, SymbolName));
123 // Return true if this is a 32-bit x86 PE COFF module.
124 bool ModuleInfo::isWin32Module() const {
125 auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
126 return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
129 uint64_t ModuleInfo::getModulePreferredBase() const {
130 if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
131 return CoffObject->getImageBase();
135 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
136 std::string &Name, uint64_t &Addr,
137 uint64_t &Size) const {
138 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
139 if (SymbolMap.empty())
141 SymbolDesc SD = { Address, Address };
142 auto SymbolIterator = SymbolMap.upper_bound(SD);
143 if (SymbolIterator == SymbolMap.begin())
146 if (SymbolIterator->first.Size != 0 &&
147 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
149 Name = SymbolIterator->second.str();
150 Addr = SymbolIterator->first.Addr;
151 Size = SymbolIterator->first.Size;
155 DILineInfo ModuleInfo::symbolizeCode(
156 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
158 if (DebugInfoContext) {
159 LineInfo = DebugInfoContext->getLineInfoForAddress(
160 ModuleOffset, getDILineInfoSpecifier(Opts));
162 // Override function name from symbol table if necessary.
163 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
164 std::string FunctionName;
165 uint64_t Start, Size;
166 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
167 FunctionName, Start, Size)) {
168 LineInfo.FunctionName = FunctionName;
174 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
175 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
176 DIInliningInfo InlinedContext;
178 if (DebugInfoContext) {
179 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
180 ModuleOffset, getDILineInfoSpecifier(Opts));
182 // Make sure there is at least one frame in context.
183 if (InlinedContext.getNumberOfFrames() == 0) {
184 InlinedContext.addFrame(DILineInfo());
186 // Override the function name in lower frame with name from symbol table.
187 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
188 DIInliningInfo PatchedInlinedContext;
189 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
190 DILineInfo LineInfo = InlinedContext.getFrame(i);
192 std::string FunctionName;
193 uint64_t Start, Size;
194 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
195 FunctionName, Start, Size)) {
196 LineInfo.FunctionName = FunctionName;
199 PatchedInlinedContext.addFrame(LineInfo);
201 InlinedContext = PatchedInlinedContext;
203 return InlinedContext;
206 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
207 uint64_t &Start, uint64_t &Size) const {
208 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
212 const char LLVMSymbolizer::kBadString[] = "??";
214 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
215 uint64_t ModuleOffset) {
216 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
218 return printDILineInfo(DILineInfo(), Info);
220 // If the user is giving us relative addresses, add the preferred base of the
221 // object to the offset before we do the query. It's what DIContext expects.
222 if (Opts.RelativeAddresses)
223 ModuleOffset += Info->getModulePreferredBase();
225 if (Opts.PrintInlining) {
226 DIInliningInfo InlinedContext =
227 Info->symbolizeInlinedCode(ModuleOffset, Opts);
228 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
229 assert(FramesNum > 0);
231 for (uint32_t i = 0; i < FramesNum; i++) {
232 DILineInfo LineInfo = InlinedContext.getFrame(i);
233 Result += printDILineInfo(LineInfo, Info);
237 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
238 return printDILineInfo(LineInfo, Info);
241 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
242 uint64_t ModuleOffset) {
243 std::string Name = kBadString;
246 if (Opts.UseSymbolTable) {
247 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
248 // If the user is giving us relative addresses, add the preferred base of the
249 // object to the offset before we do the query. It's what DIContext expects.
250 if (Opts.RelativeAddresses)
251 ModuleOffset += Info->getModulePreferredBase();
252 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
253 Name = DemangleName(Name, Info);
256 std::stringstream ss;
257 ss << Name << "\n" << Start << " " << Size << "\n";
261 void LLVMSymbolizer::flush() {
262 DeleteContainerSeconds(Modules);
263 ObjectPairForPathArch.clear();
264 ObjectFileForArch.clear();
267 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
268 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
269 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
270 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
272 std::string getDarwinDWARFResourceForPath(
273 const std::string &Path, const std::string &Basename) {
274 SmallString<16> ResourceName = StringRef(Path);
275 if (sys::path::extension(Path) != ".dSYM") {
276 ResourceName += ".dSYM";
278 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
279 sys::path::append(ResourceName, Basename);
280 return ResourceName.str();
283 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
284 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
285 MemoryBuffer::getFileOrSTDIN(Path);
288 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
291 static bool findDebugBinary(const std::string &OrigPath,
292 const std::string &DebuglinkName, uint32_t CRCHash,
293 std::string &Result) {
294 std::string OrigRealPath = OrigPath;
295 #if defined(HAVE_REALPATH)
296 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
301 SmallString<16> OrigDir(OrigRealPath);
302 llvm::sys::path::remove_filename(OrigDir);
303 SmallString<16> DebugPath = OrigDir;
304 // Try /path/to/original_binary/debuglink_name
305 llvm::sys::path::append(DebugPath, DebuglinkName);
306 if (checkFileCRC(DebugPath, CRCHash)) {
307 Result = DebugPath.str();
310 // Try /path/to/original_binary/.debug/debuglink_name
311 DebugPath = OrigRealPath;
312 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
313 if (checkFileCRC(DebugPath, CRCHash)) {
314 Result = DebugPath.str();
317 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
318 DebugPath = "/usr/lib/debug";
319 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
321 if (checkFileCRC(DebugPath, CRCHash)) {
322 Result = DebugPath.str();
328 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
332 for (const SectionRef &Section : Obj->sections()) {
334 Section.getName(Name);
335 Name = Name.substr(Name.find_first_not_of("._"));
336 if (Name == "gnu_debuglink") {
338 Section.getContents(Data);
339 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
341 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
342 // 4-byte align the offset.
343 Offset = (Offset + 3) & ~0x3;
344 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
345 DebugName = DebugNameStr;
346 CRCHash = DE.getU32(&Offset);
357 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
358 const MachOObjectFile *Obj) {
359 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
360 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
361 if (dbg_uuid.empty() || bin_uuid.empty())
363 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
366 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
367 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
368 // On Darwin we may find DWARF in separate object file in
369 // resource directory.
370 std::vector<std::string> DsymPaths;
371 StringRef Filename = sys::path::filename(ExePath);
372 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
373 for (const auto &Path : Opts.DsymHints) {
374 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
376 for (const auto &path : DsymPaths) {
377 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
378 std::error_code EC = BinaryOrErr.getError();
379 if (EC != errc::no_such_file_or_directory && !error(EC)) {
380 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
382 getObjectFileFromBinary(B.getBinary(), ArchName);
383 const MachOObjectFile *MachDbgObj =
384 dyn_cast<const MachOObjectFile>(DbgObj);
385 if (!MachDbgObj) continue;
386 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
387 addOwningBinary(std::move(B));
395 LLVMSymbolizer::ObjectPair
396 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
397 const std::string &ArchName) {
398 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
399 if (I != ObjectPairForPathArch.end())
401 ObjectFile *Obj = nullptr;
402 ObjectFile *DbgObj = nullptr;
403 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
404 if (!error(BinaryOrErr.getError())) {
405 OwningBinary<Binary> &B = BinaryOrErr.get();
406 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
408 ObjectPair Res = std::make_pair(nullptr, nullptr);
409 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
412 addOwningBinary(std::move(B));
413 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
414 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
415 // Try to locate the debug binary using .gnu_debuglink section.
417 std::string DebuglinkName;
419 std::string DebugBinaryPath;
420 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
421 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
422 BinaryOrErr = createBinary(DebugBinaryPath);
423 if (!error(BinaryOrErr.getError())) {
424 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
425 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
426 addOwningBinary(std::move(B));
433 ObjectPair Res = std::make_pair(Obj, DbgObj);
434 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
439 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
440 const std::string &ArchName) {
443 ObjectFile *Res = nullptr;
444 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
445 const auto &I = ObjectFileForArch.find(
446 std::make_pair(UB, ArchName));
447 if (I != ObjectFileForArch.end())
449 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
450 UB->getObjectForArch(ArchName);
452 Res = ParsedObj.get().get();
453 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
455 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
456 } else if (Bin->isObject()) {
457 Res = cast<ObjectFile>(Bin);
463 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
464 const auto &I = Modules.find(ModuleName);
465 if (I != Modules.end())
467 std::string BinaryName = ModuleName;
468 std::string ArchName = Opts.DefaultArch;
469 size_t ColonPos = ModuleName.find_last_of(':');
470 // Verify that substring after colon form a valid arch name.
471 if (ColonPos != std::string::npos) {
472 std::string ArchStr = ModuleName.substr(ColonPos + 1);
473 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
474 BinaryName = ModuleName.substr(0, ColonPos);
478 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
480 if (!Objects.first) {
481 // Failed to find valid object file.
482 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
485 DIContext *Context = nullptr;
486 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
487 // If this is a COFF object, assume it contains PDB debug information. If
488 // we don't find any we will fall back to the DWARF case.
489 std::unique_ptr<IPDBSession> Session;
490 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
491 Objects.first->getFileName(), Session);
492 if (Error == PDB_ErrorCode::Success) {
493 Context = new PDBContext(*CoffObject, std::move(Session));
497 Context = new DWARFContextInMemory(*Objects.second);
499 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
500 Modules.insert(make_pair(ModuleName, Info));
504 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
505 ModuleInfo *ModInfo) const {
506 // By default, DILineInfo contains "<invalid>" for function/filename it
507 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
508 static const std::string kDILineInfoBadString = "<invalid>";
509 std::stringstream Result;
510 if (Opts.PrintFunctions != FunctionNameKind::None) {
511 std::string FunctionName = LineInfo.FunctionName;
512 if (FunctionName == kDILineInfoBadString)
513 FunctionName = kBadString;
514 else if (Opts.Demangle)
515 FunctionName = DemangleName(FunctionName, ModInfo);
516 Result << FunctionName << "\n";
518 std::string Filename = LineInfo.FileName;
519 if (Filename == kDILineInfoBadString)
520 Filename = kBadString;
521 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
525 // Undo these various manglings for Win32 extern "C" functions:
528 // fastcall - @foo@12
529 // vectorcall - foo@@12
530 // These are all different linkage names for 'foo'.
531 static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
532 // Remove any '_' or '@' prefix.
533 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
534 if (Front == '_' || Front == '@')
535 SymbolName = SymbolName.drop_front();
537 // Remove any '@[0-9]+' suffix.
539 size_t AtPos = SymbolName.rfind('@');
540 if (AtPos != StringRef::npos &&
541 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
542 [](char C) { return C >= '0' && C <= '9'; })) {
543 SymbolName = SymbolName.substr(0, AtPos);
547 // Remove any ending '@' for vectorcall.
548 if (SymbolName.endswith("@"))
549 SymbolName = SymbolName.drop_back();
554 #if !defined(_MSC_VER)
555 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
556 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
557 size_t *length, int *status);
560 std::string LLVMSymbolizer::DemangleName(const std::string &Name,
561 ModuleInfo *ModInfo) {
562 #if !defined(_MSC_VER)
563 // We can spoil names of symbols with C linkage, so use an heuristic
564 // approach to check if the name should be demangled.
565 if (Name.substr(0, 2) == "_Z") {
567 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
570 std::string Result = DemangledName;
575 if (!Name.empty() && Name.front() == '?') {
576 // Only do MSVC C++ demangling on symbols starting with '?'.
577 char DemangledName[1024] = {0};
578 DWORD result = ::UnDecorateSymbolName(
579 Name.c_str(), DemangledName, 1023,
580 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
581 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
582 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
583 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
584 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
585 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
586 return (result == 0) ? Name : std::string(DemangledName);
589 if (ModInfo->isWin32Module())
590 return std::string(demanglePE32ExternCFunc(Name));
594 } // namespace symbolize