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/Casting.h"
24 #include "llvm/Support/Compression.h"
25 #include "llvm/Support/DataExtractor.h"
26 #include "llvm/Support/Errc.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
36 #pragma comment(lib, "dbghelp.lib")
42 static bool error(std::error_code ec) {
45 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
49 static DILineInfoSpecifier
50 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
51 return DILineInfoSpecifier(
52 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
56 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
57 : Module(Obj), DebugInfoContext(DICtx) {
58 std::unique_ptr<DataExtractor> OpdExtractor;
59 uint64_t OpdAddress = 0;
60 // Find the .opd (function descriptor) section if any, for big-endian
62 if (Module->getArch() == Triple::ppc64) {
63 for (section_iterator Section : Module->sections()) {
65 if (!error(Section->getName(Name)) && Name == ".opd") {
67 if (!error(Section->getContents(Data))) {
68 OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
69 Module->getBytesInAddress()));
70 OpdAddress = Section->getAddress();
76 std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
77 computeSymbolSizes(*Module);
78 for (auto &P : Symbols)
79 addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress);
82 void ModuleInfo::addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
83 DataExtractor *OpdExtractor, uint64_t OpdAddress) {
84 SymbolRef::Type SymbolType = Symbol.getType();
85 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
87 ErrorOr<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
88 if (error(SymbolAddressOrErr.getError()))
90 uint64_t SymbolAddress = *SymbolAddressOrErr;
91 if (SymbolAddress == UnknownAddress)
94 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
95 // function descriptors. The first word of the descriptor is a pointer to
96 // the function's code.
97 // For the purposes of symbolization, pretend the symbol's address is that
98 // of the function's code, not the descriptor.
99 uint64_t OpdOffset = SymbolAddress - OpdAddress;
100 uint32_t OpdOffset32 = OpdOffset;
101 if (OpdOffset == OpdOffset32 &&
102 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
103 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
105 ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName();
106 if (error(SymbolNameOrErr.getError()))
108 StringRef SymbolName = *SymbolNameOrErr;
109 // Mach-O symbol table names have leading underscore, skip it.
110 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
111 SymbolName = SymbolName.drop_front();
112 // FIXME: If a function has alias, there are two entries in symbol table
113 // with same address size. Make sure we choose the correct one.
114 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
115 SymbolDesc SD = { SymbolAddress, SymbolSize };
116 M.insert(std::make_pair(SD, SymbolName));
119 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
120 std::string &Name, uint64_t &Addr,
121 uint64_t &Size) const {
122 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
123 if (SymbolMap.empty())
125 SymbolDesc SD = { Address, Address };
126 auto SymbolIterator = SymbolMap.upper_bound(SD);
127 if (SymbolIterator == SymbolMap.begin())
130 if (SymbolIterator->first.Size != 0 &&
131 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
133 Name = SymbolIterator->second.str();
134 Addr = SymbolIterator->first.Addr;
135 Size = SymbolIterator->first.Size;
139 DILineInfo ModuleInfo::symbolizeCode(
140 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
142 if (DebugInfoContext) {
143 LineInfo = DebugInfoContext->getLineInfoForAddress(
144 ModuleOffset, getDILineInfoSpecifier(Opts));
146 // Override function name from symbol table if necessary.
147 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
148 std::string FunctionName;
149 uint64_t Start, Size;
150 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
151 FunctionName, Start, Size)) {
152 LineInfo.FunctionName = FunctionName;
158 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
159 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
160 DIInliningInfo InlinedContext;
162 if (DebugInfoContext) {
163 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
164 ModuleOffset, getDILineInfoSpecifier(Opts));
166 // Make sure there is at least one frame in context.
167 if (InlinedContext.getNumberOfFrames() == 0) {
168 InlinedContext.addFrame(DILineInfo());
170 // Override the function name in lower frame with name from symbol table.
171 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
172 DIInliningInfo PatchedInlinedContext;
173 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
174 DILineInfo LineInfo = InlinedContext.getFrame(i);
176 std::string FunctionName;
177 uint64_t Start, Size;
178 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
179 FunctionName, Start, Size)) {
180 LineInfo.FunctionName = FunctionName;
183 PatchedInlinedContext.addFrame(LineInfo);
185 InlinedContext = PatchedInlinedContext;
187 return InlinedContext;
190 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
191 uint64_t &Start, uint64_t &Size) const {
192 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
196 const char LLVMSymbolizer::kBadString[] = "??";
198 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
199 uint64_t ModuleOffset) {
200 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
202 return printDILineInfo(DILineInfo());
203 if (Opts.PrintInlining) {
204 DIInliningInfo InlinedContext =
205 Info->symbolizeInlinedCode(ModuleOffset, Opts);
206 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
207 assert(FramesNum > 0);
209 for (uint32_t i = 0; i < FramesNum; i++) {
210 DILineInfo LineInfo = InlinedContext.getFrame(i);
211 Result += printDILineInfo(LineInfo);
215 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
216 return printDILineInfo(LineInfo);
219 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
220 uint64_t ModuleOffset) {
221 std::string Name = kBadString;
224 if (Opts.UseSymbolTable) {
225 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
226 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
227 Name = DemangleName(Name);
230 std::stringstream ss;
231 ss << Name << "\n" << Start << " " << Size << "\n";
235 void LLVMSymbolizer::flush() {
236 DeleteContainerSeconds(Modules);
237 ObjectPairForPathArch.clear();
238 ObjectFileForArch.clear();
241 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
242 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
243 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
244 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
246 std::string getDarwinDWARFResourceForPath(
247 const std::string &Path, const std::string &Basename) {
248 SmallString<16> ResourceName = StringRef(Path);
249 if (sys::path::extension(Path) != ".dSYM") {
250 ResourceName += ".dSYM";
252 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
253 sys::path::append(ResourceName, Basename);
254 return ResourceName.str();
257 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
258 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
259 MemoryBuffer::getFileOrSTDIN(Path);
262 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
265 static bool findDebugBinary(const std::string &OrigPath,
266 const std::string &DebuglinkName, uint32_t CRCHash,
267 std::string &Result) {
268 std::string OrigRealPath = OrigPath;
269 #if defined(HAVE_REALPATH)
270 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
275 SmallString<16> OrigDir(OrigRealPath);
276 llvm::sys::path::remove_filename(OrigDir);
277 SmallString<16> DebugPath = OrigDir;
278 // Try /path/to/original_binary/debuglink_name
279 llvm::sys::path::append(DebugPath, DebuglinkName);
280 if (checkFileCRC(DebugPath, CRCHash)) {
281 Result = DebugPath.str();
284 // Try /path/to/original_binary/.debug/debuglink_name
285 DebugPath = OrigRealPath;
286 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
287 if (checkFileCRC(DebugPath, CRCHash)) {
288 Result = DebugPath.str();
291 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
292 DebugPath = "/usr/lib/debug";
293 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
295 if (checkFileCRC(DebugPath, CRCHash)) {
296 Result = DebugPath.str();
302 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
306 for (const SectionRef &Section : Obj->sections()) {
308 Section.getName(Name);
309 Name = Name.substr(Name.find_first_not_of("._"));
310 if (Name == "gnu_debuglink") {
312 Section.getContents(Data);
313 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
315 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
316 // 4-byte align the offset.
317 Offset = (Offset + 3) & ~0x3;
318 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
319 DebugName = DebugNameStr;
320 CRCHash = DE.getU32(&Offset);
331 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
332 const MachOObjectFile *Obj) {
333 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
334 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
335 if (dbg_uuid.empty() || bin_uuid.empty())
337 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
340 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
341 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
342 // On Darwin we may find DWARF in separate object file in
343 // resource directory.
344 std::vector<std::string> DsymPaths;
345 StringRef Filename = sys::path::filename(ExePath);
346 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
347 for (const auto &Path : Opts.DsymHints) {
348 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
350 for (const auto &path : DsymPaths) {
351 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
352 std::error_code EC = BinaryOrErr.getError();
353 if (EC != errc::no_such_file_or_directory && !error(EC)) {
354 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
356 getObjectFileFromBinary(B.getBinary(), ArchName);
357 const MachOObjectFile *MachDbgObj =
358 dyn_cast<const MachOObjectFile>(DbgObj);
359 if (!MachDbgObj) continue;
360 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
361 addOwningBinary(std::move(B));
369 LLVMSymbolizer::ObjectPair
370 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
371 const std::string &ArchName) {
372 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
373 if (I != ObjectPairForPathArch.end())
375 ObjectFile *Obj = nullptr;
376 ObjectFile *DbgObj = nullptr;
377 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
378 if (!error(BinaryOrErr.getError())) {
379 OwningBinary<Binary> &B = BinaryOrErr.get();
380 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
382 ObjectPair Res = std::make_pair(nullptr, nullptr);
383 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
386 addOwningBinary(std::move(B));
387 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
388 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
389 // Try to locate the debug binary using .gnu_debuglink section.
391 std::string DebuglinkName;
393 std::string DebugBinaryPath;
394 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
395 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
396 BinaryOrErr = createBinary(DebugBinaryPath);
397 if (!error(BinaryOrErr.getError())) {
398 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
399 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
400 addOwningBinary(std::move(B));
407 ObjectPair Res = std::make_pair(Obj, DbgObj);
408 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
413 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
414 const std::string &ArchName) {
417 ObjectFile *Res = nullptr;
418 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
419 const auto &I = ObjectFileForArch.find(
420 std::make_pair(UB, ArchName));
421 if (I != ObjectFileForArch.end())
423 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
424 UB->getObjectForArch(ArchName);
426 Res = ParsedObj.get().get();
427 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
429 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
430 } else if (Bin->isObject()) {
431 Res = cast<ObjectFile>(Bin);
437 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
438 const auto &I = Modules.find(ModuleName);
439 if (I != Modules.end())
441 std::string BinaryName = ModuleName;
442 std::string ArchName = Opts.DefaultArch;
443 size_t ColonPos = ModuleName.find_last_of(':');
444 // Verify that substring after colon form a valid arch name.
445 if (ColonPos != std::string::npos) {
446 std::string ArchStr = ModuleName.substr(ColonPos + 1);
447 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
448 BinaryName = ModuleName.substr(0, ColonPos);
452 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
454 if (!Objects.first) {
455 // Failed to find valid object file.
456 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
459 DIContext *Context = nullptr;
460 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
461 // If this is a COFF object, assume it contains PDB debug information. If
462 // we don't find any we will fall back to the DWARF case.
463 std::unique_ptr<IPDBSession> Session;
464 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
465 Objects.first->getFileName(), Session);
466 if (Error == PDB_ErrorCode::Success) {
467 Context = new PDBContext(*CoffObject, std::move(Session),
468 Opts.RelativeAddresses);
472 Context = new DWARFContextInMemory(*Objects.second);
474 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
475 Modules.insert(make_pair(ModuleName, Info));
479 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
480 // By default, DILineInfo contains "<invalid>" for function/filename it
481 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
482 static const std::string kDILineInfoBadString = "<invalid>";
483 std::stringstream Result;
484 if (Opts.PrintFunctions != FunctionNameKind::None) {
485 std::string FunctionName = LineInfo.FunctionName;
486 if (FunctionName == kDILineInfoBadString)
487 FunctionName = kBadString;
488 else if (Opts.Demangle)
489 FunctionName = DemangleName(FunctionName);
490 Result << FunctionName << "\n";
492 std::string Filename = LineInfo.FileName;
493 if (Filename == kDILineInfoBadString)
494 Filename = kBadString;
495 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
499 #if !defined(_MSC_VER)
500 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
501 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
502 size_t *length, int *status);
505 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
506 #if !defined(_MSC_VER)
507 // We can spoil names of symbols with C linkage, so use an heuristic
508 // approach to check if the name should be demangled.
509 if (Name.substr(0, 2) != "_Z")
512 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
515 std::string Result = DemangledName;
519 char DemangledName[1024] = {0};
520 DWORD result = ::UnDecorateSymbolName(
521 Name.c_str(), DemangledName, 1023,
522 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
523 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
524 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
525 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
526 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
527 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
529 return (result == 0) ? Name : std::string(DemangledName);
533 } // namespace symbolize