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/Support/Casting.h"
23 #include "llvm/Support/Compression.h"
24 #include "llvm/Support/DataExtractor.h"
25 #include "llvm/Support/Errc.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
40 static bool error(std::error_code ec) {
43 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
47 static DILineInfoSpecifier
48 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
49 return DILineInfoSpecifier(
50 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
54 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
55 : Module(Obj), DebugInfoContext(DICtx) {
56 std::unique_ptr<DataExtractor> OpdExtractor;
57 uint64_t OpdAddress = 0;
58 // Find the .opd (function descriptor) section if any, for big-endian
60 if (Module->getArch() == Triple::ppc64) {
61 for (section_iterator Section : Module->sections()) {
63 if (!error(Section->getName(Name)) && Name == ".opd") {
65 if (!error(Section->getContents(Data))) {
66 OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
67 Module->getBytesInAddress()));
68 OpdAddress = Section->getAddress();
74 for (const SymbolRef &Symbol : Module->symbols()) {
75 addSymbol(Symbol, OpdExtractor.get(), OpdAddress);
77 bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
78 if (NoSymbolTable && Module->isELF()) {
79 // Fallback to dynamic symbol table, if regular symbol table is stripped.
80 auto IDyn = cast<ELFObjectFileBase>(Module)->getDynamicSymbolIterators();
81 for (SymbolRef Sym : IDyn) {
82 addSymbol(Sym, OpdExtractor.get(), OpdAddress);
87 void ModuleInfo::addSymbol(const SymbolRef &Symbol, DataExtractor *OpdExtractor,
88 uint64_t OpdAddress) {
89 SymbolRef::Type SymbolType;
90 if (error(Symbol.getType(SymbolType)))
92 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
94 uint64_t SymbolAddress;
95 if (error(Symbol.getAddress(SymbolAddress)) ||
96 SymbolAddress == UnknownAddress)
99 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
100 // function descriptors. The first word of the descriptor is a pointer to
101 // the function's code.
102 // For the purposes of symbolization, pretend the symbol's address is that
103 // of the function's code, not the descriptor.
104 uint64_t OpdOffset = SymbolAddress - OpdAddress;
105 uint32_t OpdOffset32 = OpdOffset;
106 if (OpdOffset == OpdOffset32 &&
107 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
108 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
111 // Onyl ELF has a size for every symbol so assume that symbol occupies the
112 // memory range up to the following symbol.
113 if (auto *E = dyn_cast<ELFObjectFileBase>(Module))
114 SymbolSize = E->getSymbolSize(Symbol);
117 StringRef SymbolName;
118 if (error(Symbol.getName(SymbolName)))
120 // Mach-O symbol table names have leading underscore, skip it.
121 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
122 SymbolName = SymbolName.drop_front();
123 // FIXME: If a function has alias, there are two entries in symbol table
124 // with same address size. Make sure we choose the correct one.
125 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
126 SymbolDesc SD = { SymbolAddress, SymbolSize };
127 M.insert(std::make_pair(SD, SymbolName));
130 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
131 std::string &Name, uint64_t &Addr,
132 uint64_t &Size) const {
133 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
134 if (SymbolMap.empty())
136 SymbolDesc SD = { Address, Address };
137 auto SymbolIterator = SymbolMap.upper_bound(SD);
138 if (SymbolIterator == SymbolMap.begin())
141 if (SymbolIterator->first.Size != 0 &&
142 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
144 Name = SymbolIterator->second.str();
145 Addr = SymbolIterator->first.Addr;
146 Size = SymbolIterator->first.Size;
150 DILineInfo ModuleInfo::symbolizeCode(
151 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
153 if (DebugInfoContext) {
154 LineInfo = DebugInfoContext->getLineInfoForAddress(
155 ModuleOffset, getDILineInfoSpecifier(Opts));
157 // Override function name from symbol table if necessary.
158 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
159 std::string FunctionName;
160 uint64_t Start, Size;
161 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
162 FunctionName, Start, Size)) {
163 LineInfo.FunctionName = FunctionName;
169 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
170 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
171 DIInliningInfo InlinedContext;
173 if (DebugInfoContext) {
174 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
175 ModuleOffset, getDILineInfoSpecifier(Opts));
177 // Make sure there is at least one frame in context.
178 if (InlinedContext.getNumberOfFrames() == 0) {
179 InlinedContext.addFrame(DILineInfo());
181 // Override the function name in lower frame with name from symbol table.
182 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
183 DIInliningInfo PatchedInlinedContext;
184 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
185 DILineInfo LineInfo = InlinedContext.getFrame(i);
187 std::string FunctionName;
188 uint64_t Start, Size;
189 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
190 FunctionName, Start, Size)) {
191 LineInfo.FunctionName = FunctionName;
194 PatchedInlinedContext.addFrame(LineInfo);
196 InlinedContext = PatchedInlinedContext;
198 return InlinedContext;
201 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
202 uint64_t &Start, uint64_t &Size) const {
203 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
207 const char LLVMSymbolizer::kBadString[] = "??";
209 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
210 uint64_t ModuleOffset) {
211 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
213 return printDILineInfo(DILineInfo());
214 if (Opts.PrintInlining) {
215 DIInliningInfo InlinedContext =
216 Info->symbolizeInlinedCode(ModuleOffset, Opts);
217 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
218 assert(FramesNum > 0);
220 for (uint32_t i = 0; i < FramesNum; i++) {
221 DILineInfo LineInfo = InlinedContext.getFrame(i);
222 Result += printDILineInfo(LineInfo);
226 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
227 return printDILineInfo(LineInfo);
230 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
231 uint64_t ModuleOffset) {
232 std::string Name = kBadString;
235 if (Opts.UseSymbolTable) {
236 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
237 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
238 Name = DemangleName(Name);
241 std::stringstream ss;
242 ss << Name << "\n" << Start << " " << Size << "\n";
246 void LLVMSymbolizer::flush() {
247 DeleteContainerSeconds(Modules);
248 ObjectPairForPathArch.clear();
249 ObjectFileForArch.clear();
252 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
253 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
254 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
255 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
257 std::string getDarwinDWARFResourceForPath(
258 const std::string &Path, const std::string &Basename) {
259 SmallString<16> ResourceName = StringRef(Path);
260 if (sys::path::extension(Path) != ".dSYM") {
261 ResourceName += ".dSYM";
263 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
264 sys::path::append(ResourceName, Basename);
265 return ResourceName.str();
268 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
269 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
270 MemoryBuffer::getFileOrSTDIN(Path);
273 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
276 static bool findDebugBinary(const std::string &OrigPath,
277 const std::string &DebuglinkName, uint32_t CRCHash,
278 std::string &Result) {
279 std::string OrigRealPath = OrigPath;
280 #if defined(HAVE_REALPATH)
281 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
286 SmallString<16> OrigDir(OrigRealPath);
287 llvm::sys::path::remove_filename(OrigDir);
288 SmallString<16> DebugPath = OrigDir;
289 // Try /path/to/original_binary/debuglink_name
290 llvm::sys::path::append(DebugPath, DebuglinkName);
291 if (checkFileCRC(DebugPath, CRCHash)) {
292 Result = DebugPath.str();
295 // Try /path/to/original_binary/.debug/debuglink_name
296 DebugPath = OrigRealPath;
297 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
298 if (checkFileCRC(DebugPath, CRCHash)) {
299 Result = DebugPath.str();
302 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
303 DebugPath = "/usr/lib/debug";
304 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
306 if (checkFileCRC(DebugPath, CRCHash)) {
307 Result = DebugPath.str();
313 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
317 for (const SectionRef &Section : Obj->sections()) {
319 Section.getName(Name);
320 Name = Name.substr(Name.find_first_not_of("._"));
321 if (Name == "gnu_debuglink") {
323 Section.getContents(Data);
324 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
326 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
327 // 4-byte align the offset.
328 Offset = (Offset + 3) & ~0x3;
329 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
330 DebugName = DebugNameStr;
331 CRCHash = DE.getU32(&Offset);
342 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
343 const MachOObjectFile *Obj) {
344 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
345 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
346 if (dbg_uuid.empty() || bin_uuid.empty())
348 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
351 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
352 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
353 // On Darwin we may find DWARF in separate object file in
354 // resource directory.
355 std::vector<std::string> DsymPaths;
356 StringRef Filename = sys::path::filename(ExePath);
357 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
358 for (const auto &Path : Opts.DsymHints) {
359 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
361 for (const auto &path : DsymPaths) {
362 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
363 std::error_code EC = BinaryOrErr.getError();
364 if (EC != errc::no_such_file_or_directory && !error(EC)) {
365 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
367 getObjectFileFromBinary(B.getBinary(), ArchName);
368 const MachOObjectFile *MachDbgObj =
369 dyn_cast<const MachOObjectFile>(DbgObj);
370 if (!MachDbgObj) continue;
371 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
372 addOwningBinary(std::move(B));
380 LLVMSymbolizer::ObjectPair
381 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
382 const std::string &ArchName) {
383 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
384 if (I != ObjectPairForPathArch.end())
386 ObjectFile *Obj = nullptr;
387 ObjectFile *DbgObj = nullptr;
388 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
389 if (!error(BinaryOrErr.getError())) {
390 OwningBinary<Binary> &B = BinaryOrErr.get();
391 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
393 ObjectPair Res = std::make_pair(nullptr, nullptr);
394 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
397 addOwningBinary(std::move(B));
398 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
399 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
400 // Try to locate the debug binary using .gnu_debuglink section.
402 std::string DebuglinkName;
404 std::string DebugBinaryPath;
405 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
406 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
407 BinaryOrErr = createBinary(DebugBinaryPath);
408 if (!error(BinaryOrErr.getError())) {
409 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
410 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
411 addOwningBinary(std::move(B));
418 ObjectPair Res = std::make_pair(Obj, DbgObj);
419 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
424 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
425 const std::string &ArchName) {
428 ObjectFile *Res = nullptr;
429 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
430 const auto &I = ObjectFileForArch.find(
431 std::make_pair(UB, ArchName));
432 if (I != ObjectFileForArch.end())
434 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
435 UB->getObjectForArch(ArchName);
437 Res = ParsedObj.get().get();
438 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
440 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
441 } else if (Bin->isObject()) {
442 Res = cast<ObjectFile>(Bin);
448 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
449 const auto &I = Modules.find(ModuleName);
450 if (I != Modules.end())
452 std::string BinaryName = ModuleName;
453 std::string ArchName = Opts.DefaultArch;
454 size_t ColonPos = ModuleName.find_last_of(':');
455 // Verify that substring after colon form a valid arch name.
456 if (ColonPos != std::string::npos) {
457 std::string ArchStr = ModuleName.substr(ColonPos + 1);
458 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
459 BinaryName = ModuleName.substr(0, ColonPos);
463 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
465 if (!Objects.first) {
466 // Failed to find valid object file.
467 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
470 DIContext *Context = nullptr;
471 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
472 // If this is a COFF object, assume it contains PDB debug information. If
473 // we don't find any we will fall back to the DWARF case.
474 std::unique_ptr<IPDBSession> Session;
475 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
476 Objects.first->getFileName(), Session);
477 if (Error == PDB_ErrorCode::Success) {
478 Context = new PDBContext(*CoffObject, std::move(Session),
479 Opts.RelativeAddresses);
483 Context = new DWARFContextInMemory(*Objects.second);
485 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
486 Modules.insert(make_pair(ModuleName, Info));
490 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) 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);
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 #if !defined(_MSC_VER)
511 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
512 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
513 size_t *length, int *status);
516 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
517 #if !defined(_MSC_VER)
518 // We can spoil names of symbols with C linkage, so use an heuristic
519 // approach to check if the name should be demangled.
520 if (Name.substr(0, 2) != "_Z")
523 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
526 std::string Result = DemangledName;
530 char DemangledName[1024] = {0};
531 DWORD result = ::UnDecorateSymbolName(
532 Name.c_str(), DemangledName, 1023,
533 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
534 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
535 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
536 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
537 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
538 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
540 return (result == 0) ? Name : std::string(DemangledName);
544 } // namespace symbolize