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 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
130 std::string &Name, uint64_t &Addr,
131 uint64_t &Size) const {
132 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
133 if (SymbolMap.empty())
135 SymbolDesc SD = { Address, Address };
136 auto SymbolIterator = SymbolMap.upper_bound(SD);
137 if (SymbolIterator == SymbolMap.begin())
140 if (SymbolIterator->first.Size != 0 &&
141 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
143 Name = SymbolIterator->second.str();
144 Addr = SymbolIterator->first.Addr;
145 Size = SymbolIterator->first.Size;
149 DILineInfo ModuleInfo::symbolizeCode(
150 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
152 if (DebugInfoContext) {
153 LineInfo = DebugInfoContext->getLineInfoForAddress(
154 ModuleOffset, getDILineInfoSpecifier(Opts));
156 // Override function name from symbol table if necessary.
157 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
158 std::string FunctionName;
159 uint64_t Start, Size;
160 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
161 FunctionName, Start, Size)) {
162 LineInfo.FunctionName = FunctionName;
168 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
169 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
170 DIInliningInfo InlinedContext;
172 if (DebugInfoContext) {
173 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
174 ModuleOffset, getDILineInfoSpecifier(Opts));
176 // Make sure there is at least one frame in context.
177 if (InlinedContext.getNumberOfFrames() == 0) {
178 InlinedContext.addFrame(DILineInfo());
180 // Override the function name in lower frame with name from symbol table.
181 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
182 DIInliningInfo PatchedInlinedContext;
183 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
184 DILineInfo LineInfo = InlinedContext.getFrame(i);
186 std::string FunctionName;
187 uint64_t Start, Size;
188 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
189 FunctionName, Start, Size)) {
190 LineInfo.FunctionName = FunctionName;
193 PatchedInlinedContext.addFrame(LineInfo);
195 InlinedContext = PatchedInlinedContext;
197 return InlinedContext;
200 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
201 uint64_t &Start, uint64_t &Size) const {
202 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
206 const char LLVMSymbolizer::kBadString[] = "??";
208 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
209 uint64_t ModuleOffset) {
210 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
212 return printDILineInfo(DILineInfo(), Info);
213 if (Opts.PrintInlining) {
214 DIInliningInfo InlinedContext =
215 Info->symbolizeInlinedCode(ModuleOffset, Opts);
216 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
217 assert(FramesNum > 0);
219 for (uint32_t i = 0; i < FramesNum; i++) {
220 DILineInfo LineInfo = InlinedContext.getFrame(i);
221 Result += printDILineInfo(LineInfo, Info);
225 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
226 return printDILineInfo(LineInfo, Info);
229 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
230 uint64_t ModuleOffset) {
231 std::string Name = kBadString;
234 if (Opts.UseSymbolTable) {
235 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
236 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
237 Name = DemangleName(Name, Info);
240 std::stringstream ss;
241 ss << Name << "\n" << Start << " " << Size << "\n";
245 void LLVMSymbolizer::flush() {
246 DeleteContainerSeconds(Modules);
247 ObjectPairForPathArch.clear();
248 ObjectFileForArch.clear();
251 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
252 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
253 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
254 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
256 std::string getDarwinDWARFResourceForPath(
257 const std::string &Path, const std::string &Basename) {
258 SmallString<16> ResourceName = StringRef(Path);
259 if (sys::path::extension(Path) != ".dSYM") {
260 ResourceName += ".dSYM";
262 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
263 sys::path::append(ResourceName, Basename);
264 return ResourceName.str();
267 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
268 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
269 MemoryBuffer::getFileOrSTDIN(Path);
272 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
275 static bool findDebugBinary(const std::string &OrigPath,
276 const std::string &DebuglinkName, uint32_t CRCHash,
277 std::string &Result) {
278 std::string OrigRealPath = OrigPath;
279 #if defined(HAVE_REALPATH)
280 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
285 SmallString<16> OrigDir(OrigRealPath);
286 llvm::sys::path::remove_filename(OrigDir);
287 SmallString<16> DebugPath = OrigDir;
288 // Try /path/to/original_binary/debuglink_name
289 llvm::sys::path::append(DebugPath, DebuglinkName);
290 if (checkFileCRC(DebugPath, CRCHash)) {
291 Result = DebugPath.str();
294 // Try /path/to/original_binary/.debug/debuglink_name
295 DebugPath = OrigRealPath;
296 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
297 if (checkFileCRC(DebugPath, CRCHash)) {
298 Result = DebugPath.str();
301 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
302 DebugPath = "/usr/lib/debug";
303 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
305 if (checkFileCRC(DebugPath, CRCHash)) {
306 Result = DebugPath.str();
312 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
316 for (const SectionRef &Section : Obj->sections()) {
318 Section.getName(Name);
319 Name = Name.substr(Name.find_first_not_of("._"));
320 if (Name == "gnu_debuglink") {
322 Section.getContents(Data);
323 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
325 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
326 // 4-byte align the offset.
327 Offset = (Offset + 3) & ~0x3;
328 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
329 DebugName = DebugNameStr;
330 CRCHash = DE.getU32(&Offset);
341 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
342 const MachOObjectFile *Obj) {
343 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
344 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
345 if (dbg_uuid.empty() || bin_uuid.empty())
347 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
350 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
351 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
352 // On Darwin we may find DWARF in separate object file in
353 // resource directory.
354 std::vector<std::string> DsymPaths;
355 StringRef Filename = sys::path::filename(ExePath);
356 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
357 for (const auto &Path : Opts.DsymHints) {
358 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
360 for (const auto &path : DsymPaths) {
361 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
362 std::error_code EC = BinaryOrErr.getError();
363 if (EC != errc::no_such_file_or_directory && !error(EC)) {
364 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
366 getObjectFileFromBinary(B.getBinary(), ArchName);
367 const MachOObjectFile *MachDbgObj =
368 dyn_cast<const MachOObjectFile>(DbgObj);
369 if (!MachDbgObj) continue;
370 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
371 addOwningBinary(std::move(B));
379 LLVMSymbolizer::ObjectPair
380 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
381 const std::string &ArchName) {
382 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
383 if (I != ObjectPairForPathArch.end())
385 ObjectFile *Obj = nullptr;
386 ObjectFile *DbgObj = nullptr;
387 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
388 if (!error(BinaryOrErr.getError())) {
389 OwningBinary<Binary> &B = BinaryOrErr.get();
390 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
392 ObjectPair Res = std::make_pair(nullptr, nullptr);
393 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
396 addOwningBinary(std::move(B));
397 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
398 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
399 // Try to locate the debug binary using .gnu_debuglink section.
401 std::string DebuglinkName;
403 std::string DebugBinaryPath;
404 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
405 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
406 BinaryOrErr = createBinary(DebugBinaryPath);
407 if (!error(BinaryOrErr.getError())) {
408 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
409 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
410 addOwningBinary(std::move(B));
417 ObjectPair Res = std::make_pair(Obj, DbgObj);
418 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
423 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
424 const std::string &ArchName) {
427 ObjectFile *Res = nullptr;
428 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
429 const auto &I = ObjectFileForArch.find(
430 std::make_pair(UB, ArchName));
431 if (I != ObjectFileForArch.end())
433 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
434 UB->getObjectForArch(ArchName);
436 Res = ParsedObj.get().get();
437 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
439 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
440 } else if (Bin->isObject()) {
441 Res = cast<ObjectFile>(Bin);
447 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
448 const auto &I = Modules.find(ModuleName);
449 if (I != Modules.end())
451 std::string BinaryName = ModuleName;
452 std::string ArchName = Opts.DefaultArch;
453 size_t ColonPos = ModuleName.find_last_of(':');
454 // Verify that substring after colon form a valid arch name.
455 if (ColonPos != std::string::npos) {
456 std::string ArchStr = ModuleName.substr(ColonPos + 1);
457 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
458 BinaryName = ModuleName.substr(0, ColonPos);
462 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
464 if (!Objects.first) {
465 // Failed to find valid object file.
466 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
469 DIContext *Context = nullptr;
470 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
471 // If this is a COFF object, assume it contains PDB debug information. If
472 // we don't find any we will fall back to the DWARF case.
473 std::unique_ptr<IPDBSession> Session;
474 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
475 Objects.first->getFileName(), Session);
476 if (Error == PDB_ErrorCode::Success) {
477 Context = new PDBContext(*CoffObject, std::move(Session),
478 Opts.RelativeAddresses);
482 Context = new DWARFContextInMemory(*Objects.second);
484 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
485 Modules.insert(make_pair(ModuleName, Info));
489 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
490 ModuleInfo *ModInfo) const {
491 // By default, DILineInfo contains "<invalid>" for function/filename it
492 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
493 static const std::string kDILineInfoBadString = "<invalid>";
494 std::stringstream Result;
495 if (Opts.PrintFunctions != FunctionNameKind::None) {
496 std::string FunctionName = LineInfo.FunctionName;
497 if (FunctionName == kDILineInfoBadString)
498 FunctionName = kBadString;
499 else if (Opts.Demangle)
500 FunctionName = DemangleName(FunctionName, ModInfo);
501 Result << FunctionName << "\n";
503 std::string Filename = LineInfo.FileName;
504 if (Filename == kDILineInfoBadString)
505 Filename = kBadString;
506 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
510 // Undo these various manglings for Win32 extern "C" functions:
513 // fastcall - @foo@12
514 // vectorcall - foo@@12
515 // These are all different linkage names for 'foo'.
516 static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
517 // Remove any '_' or '@' prefix.
518 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
519 if (Front == '_' || Front == '@')
520 SymbolName = SymbolName.drop_front();
522 // Remove any '@[0-9]+' suffix.
524 size_t AtPos = SymbolName.rfind('@');
525 if (AtPos != StringRef::npos &&
526 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
527 [](char C) { return C >= '0' && C <= '9'; })) {
528 SymbolName = SymbolName.substr(0, AtPos);
532 // Remove any ending '@' for vectorcall.
533 if (SymbolName.endswith("@"))
534 SymbolName = SymbolName.drop_back();
539 #if !defined(_MSC_VER)
540 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
541 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
542 size_t *length, int *status);
545 std::string LLVMSymbolizer::DemangleName(const std::string &Name,
546 ModuleInfo *ModInfo) {
547 #if !defined(_MSC_VER)
548 // We can spoil names of symbols with C linkage, so use an heuristic
549 // approach to check if the name should be demangled.
550 if (Name.substr(0, 2) == "_Z") {
552 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
555 std::string Result = DemangledName;
560 if (!Name.empty() && Name.front() == '?') {
561 // Only do MSVC C++ demangling on symbols starting with '?'.
562 char DemangledName[1024] = {0};
563 DWORD result = ::UnDecorateSymbolName(
564 Name.c_str(), DemangledName, 1023,
565 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
566 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
567 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
568 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
569 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
570 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
571 return (result == 0) ? Name : std::string(DemangledName);
574 if (ModInfo->isWin32Module())
575 return std::string(demanglePE32ExternCFunc(Name));
579 } // namespace symbolize