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 if (auto Base = CoffObject->getImageBase())
136 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
137 std::string &Name, uint64_t &Addr,
138 uint64_t &Size) const {
139 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
140 if (SymbolMap.empty())
142 SymbolDesc SD = { Address, Address };
143 auto SymbolIterator = SymbolMap.upper_bound(SD);
144 if (SymbolIterator == SymbolMap.begin())
147 if (SymbolIterator->first.Size != 0 &&
148 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
150 Name = SymbolIterator->second.str();
151 Addr = SymbolIterator->first.Addr;
152 Size = SymbolIterator->first.Size;
156 DILineInfo ModuleInfo::symbolizeCode(
157 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
159 if (DebugInfoContext) {
160 LineInfo = DebugInfoContext->getLineInfoForAddress(
161 ModuleOffset, getDILineInfoSpecifier(Opts));
163 // Override function name from symbol table if necessary.
164 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
165 std::string FunctionName;
166 uint64_t Start, Size;
167 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
168 FunctionName, Start, Size)) {
169 LineInfo.FunctionName = FunctionName;
175 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
176 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
177 DIInliningInfo InlinedContext;
179 if (DebugInfoContext) {
180 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
181 ModuleOffset, getDILineInfoSpecifier(Opts));
183 // Make sure there is at least one frame in context.
184 if (InlinedContext.getNumberOfFrames() == 0) {
185 InlinedContext.addFrame(DILineInfo());
187 // Override the function name in lower frame with name from symbol table.
188 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
189 DIInliningInfo PatchedInlinedContext;
190 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
191 DILineInfo LineInfo = InlinedContext.getFrame(i);
193 std::string FunctionName;
194 uint64_t Start, Size;
195 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
196 FunctionName, Start, Size)) {
197 LineInfo.FunctionName = FunctionName;
200 PatchedInlinedContext.addFrame(LineInfo);
202 InlinedContext = PatchedInlinedContext;
204 return InlinedContext;
207 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
208 uint64_t &Start, uint64_t &Size) const {
209 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
213 const char LLVMSymbolizer::kBadString[] = "??";
215 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
216 uint64_t ModuleOffset) {
217 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
219 return printDILineInfo(DILineInfo(), Info);
221 // If the user is giving us relative addresses, add the preferred base of the
222 // object to the offset before we do the query. It's what DIContext expects.
223 if (Opts.RelativeAddresses)
224 ModuleOffset += Info->getModulePreferredBase();
226 if (Opts.PrintInlining) {
227 DIInliningInfo InlinedContext =
228 Info->symbolizeInlinedCode(ModuleOffset, Opts);
229 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
230 assert(FramesNum > 0);
232 for (uint32_t i = 0; i < FramesNum; i++) {
233 DILineInfo LineInfo = InlinedContext.getFrame(i);
234 Result += printDILineInfo(LineInfo, Info);
238 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
239 return printDILineInfo(LineInfo, Info);
242 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
243 uint64_t ModuleOffset) {
244 std::string Name = kBadString;
247 if (Opts.UseSymbolTable) {
248 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
249 // If the user is giving us relative addresses, add the preferred base of the
250 // object to the offset before we do the query. It's what DIContext expects.
251 if (Opts.RelativeAddresses)
252 ModuleOffset += Info->getModulePreferredBase();
253 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
254 Name = DemangleName(Name, Info);
257 std::stringstream ss;
258 ss << Name << "\n" << Start << " " << Size << "\n";
262 void LLVMSymbolizer::flush() {
263 DeleteContainerSeconds(Modules);
264 ObjectPairForPathArch.clear();
265 ObjectFileForArch.clear();
268 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
269 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
270 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
271 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
273 std::string getDarwinDWARFResourceForPath(
274 const std::string &Path, const std::string &Basename) {
275 SmallString<16> ResourceName = StringRef(Path);
276 if (sys::path::extension(Path) != ".dSYM") {
277 ResourceName += ".dSYM";
279 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
280 sys::path::append(ResourceName, Basename);
281 return ResourceName.str();
284 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
285 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
286 MemoryBuffer::getFileOrSTDIN(Path);
289 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
292 static bool findDebugBinary(const std::string &OrigPath,
293 const std::string &DebuglinkName, uint32_t CRCHash,
294 std::string &Result) {
295 std::string OrigRealPath = OrigPath;
296 #if defined(HAVE_REALPATH)
297 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
302 SmallString<16> OrigDir(OrigRealPath);
303 llvm::sys::path::remove_filename(OrigDir);
304 SmallString<16> DebugPath = OrigDir;
305 // Try /path/to/original_binary/debuglink_name
306 llvm::sys::path::append(DebugPath, DebuglinkName);
307 if (checkFileCRC(DebugPath, CRCHash)) {
308 Result = DebugPath.str();
311 // Try /path/to/original_binary/.debug/debuglink_name
312 DebugPath = OrigRealPath;
313 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
314 if (checkFileCRC(DebugPath, CRCHash)) {
315 Result = DebugPath.str();
318 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
319 DebugPath = "/usr/lib/debug";
320 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
322 if (checkFileCRC(DebugPath, CRCHash)) {
323 Result = DebugPath.str();
329 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
333 for (const SectionRef &Section : Obj->sections()) {
335 Section.getName(Name);
336 Name = Name.substr(Name.find_first_not_of("._"));
337 if (Name == "gnu_debuglink") {
339 Section.getContents(Data);
340 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
342 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
343 // 4-byte align the offset.
344 Offset = (Offset + 3) & ~0x3;
345 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
346 DebugName = DebugNameStr;
347 CRCHash = DE.getU32(&Offset);
358 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
359 const MachOObjectFile *Obj) {
360 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
361 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
362 if (dbg_uuid.empty() || bin_uuid.empty())
364 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
367 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
368 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
369 // On Darwin we may find DWARF in separate object file in
370 // resource directory.
371 std::vector<std::string> DsymPaths;
372 StringRef Filename = sys::path::filename(ExePath);
373 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
374 for (const auto &Path : Opts.DsymHints) {
375 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
377 for (const auto &path : DsymPaths) {
378 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
379 std::error_code EC = BinaryOrErr.getError();
380 if (EC != errc::no_such_file_or_directory && !error(EC)) {
381 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
383 getObjectFileFromBinary(B.getBinary(), ArchName);
384 const MachOObjectFile *MachDbgObj =
385 dyn_cast<const MachOObjectFile>(DbgObj);
386 if (!MachDbgObj) continue;
387 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
388 addOwningBinary(std::move(B));
396 LLVMSymbolizer::ObjectPair
397 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
398 const std::string &ArchName) {
399 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
400 if (I != ObjectPairForPathArch.end())
402 ObjectFile *Obj = nullptr;
403 ObjectFile *DbgObj = nullptr;
404 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
405 if (!error(BinaryOrErr.getError())) {
406 OwningBinary<Binary> &B = BinaryOrErr.get();
407 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
409 ObjectPair Res = std::make_pair(nullptr, nullptr);
410 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
413 addOwningBinary(std::move(B));
414 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
415 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
416 // Try to locate the debug binary using .gnu_debuglink section.
418 std::string DebuglinkName;
420 std::string DebugBinaryPath;
421 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
422 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
423 BinaryOrErr = createBinary(DebugBinaryPath);
424 if (!error(BinaryOrErr.getError())) {
425 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
426 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
427 addOwningBinary(std::move(B));
434 ObjectPair Res = std::make_pair(Obj, DbgObj);
435 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
440 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
441 const std::string &ArchName) {
444 ObjectFile *Res = nullptr;
445 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
446 const auto &I = ObjectFileForArch.find(
447 std::make_pair(UB, ArchName));
448 if (I != ObjectFileForArch.end())
450 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
451 UB->getObjectForArch(ArchName);
453 Res = ParsedObj.get().get();
454 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
456 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
457 } else if (Bin->isObject()) {
458 Res = cast<ObjectFile>(Bin);
464 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
465 const auto &I = Modules.find(ModuleName);
466 if (I != Modules.end())
468 std::string BinaryName = ModuleName;
469 std::string ArchName = Opts.DefaultArch;
470 size_t ColonPos = ModuleName.find_last_of(':');
471 // Verify that substring after colon form a valid arch name.
472 if (ColonPos != std::string::npos) {
473 std::string ArchStr = ModuleName.substr(ColonPos + 1);
474 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
475 BinaryName = ModuleName.substr(0, ColonPos);
479 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
481 if (!Objects.first) {
482 // Failed to find valid object file.
483 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
486 DIContext *Context = nullptr;
487 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
488 // If this is a COFF object, assume it contains PDB debug information. If
489 // we don't find any we will fall back to the DWARF case.
490 std::unique_ptr<IPDBSession> Session;
491 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
492 Objects.first->getFileName(), Session);
493 if (Error == PDB_ErrorCode::Success) {
494 Context = new PDBContext(*CoffObject, std::move(Session));
498 Context = new DWARFContextInMemory(*Objects.second);
500 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
501 Modules.insert(make_pair(ModuleName, Info));
505 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
506 ModuleInfo *ModInfo) const {
507 // By default, DILineInfo contains "<invalid>" for function/filename it
508 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
509 static const std::string kDILineInfoBadString = "<invalid>";
510 std::stringstream Result;
511 if (Opts.PrintFunctions != FunctionNameKind::None) {
512 std::string FunctionName = LineInfo.FunctionName;
513 if (FunctionName == kDILineInfoBadString)
514 FunctionName = kBadString;
515 else if (Opts.Demangle)
516 FunctionName = DemangleName(FunctionName, ModInfo);
517 Result << FunctionName << "\n";
519 std::string Filename = LineInfo.FileName;
520 if (Filename == kDILineInfoBadString)
521 Filename = kBadString;
522 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
526 // Undo these various manglings for Win32 extern "C" functions:
529 // fastcall - @foo@12
530 // vectorcall - foo@@12
531 // These are all different linkage names for 'foo'.
532 static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
533 // Remove any '_' or '@' prefix.
534 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
535 if (Front == '_' || Front == '@')
536 SymbolName = SymbolName.drop_front();
538 // Remove any '@[0-9]+' suffix.
540 size_t AtPos = SymbolName.rfind('@');
541 if (AtPos != StringRef::npos &&
542 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
543 [](char C) { return C >= '0' && C <= '9'; })) {
544 SymbolName = SymbolName.substr(0, AtPos);
548 // Remove any ending '@' for vectorcall.
549 if (SymbolName.endswith("@"))
550 SymbolName = SymbolName.drop_back();
555 #if !defined(_MSC_VER)
556 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
557 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
558 size_t *length, int *status);
561 std::string LLVMSymbolizer::DemangleName(const std::string &Name,
562 ModuleInfo *ModInfo) {
563 #if !defined(_MSC_VER)
564 // We can spoil names of symbols with C linkage, so use an heuristic
565 // approach to check if the name should be demangled.
566 if (Name.substr(0, 2) == "_Z") {
568 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
571 std::string Result = DemangledName;
576 if (!Name.empty() && Name.front() == '?') {
577 // Only do MSVC C++ demangling on symbols starting with '?'.
578 char DemangledName[1024] = {0};
579 DWORD result = ::UnDecorateSymbolName(
580 Name.c_str(), DemangledName, 1023,
581 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
582 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
583 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
584 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
585 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
586 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
587 return (result == 0) ? Name : std::string(DemangledName);
590 if (ModInfo->isWin32Module())
591 return std::string(demanglePE32ExternCFunc(Name));
595 } // namespace symbolize