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 uint64_t SymbolAddress;
88 if (error(Symbol.getAddress(SymbolAddress)) ||
89 SymbolAddress == UnknownAddress)
92 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
93 // function descriptors. The first word of the descriptor is a pointer to
94 // the function's code.
95 // For the purposes of symbolization, pretend the symbol's address is that
96 // of the function's code, not the descriptor.
97 uint64_t OpdOffset = SymbolAddress - OpdAddress;
98 uint32_t OpdOffset32 = OpdOffset;
99 if (OpdOffset == OpdOffset32 &&
100 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
101 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
103 StringRef SymbolName;
104 if (error(Symbol.getName(SymbolName)))
106 // Mach-O symbol table names have leading underscore, skip it.
107 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
108 SymbolName = SymbolName.drop_front();
109 // FIXME: If a function has alias, there are two entries in symbol table
110 // with same address size. Make sure we choose the correct one.
111 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
112 SymbolDesc SD = { SymbolAddress, SymbolSize };
113 M.insert(std::make_pair(SD, SymbolName));
116 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
117 std::string &Name, uint64_t &Addr,
118 uint64_t &Size) const {
119 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
120 if (SymbolMap.empty())
122 SymbolDesc SD = { Address, Address };
123 auto SymbolIterator = SymbolMap.upper_bound(SD);
124 if (SymbolIterator == SymbolMap.begin())
127 if (SymbolIterator->first.Size != 0 &&
128 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
130 Name = SymbolIterator->second.str();
131 Addr = SymbolIterator->first.Addr;
132 Size = SymbolIterator->first.Size;
136 DILineInfo ModuleInfo::symbolizeCode(
137 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
139 if (DebugInfoContext) {
140 LineInfo = DebugInfoContext->getLineInfoForAddress(
141 ModuleOffset, getDILineInfoSpecifier(Opts));
143 // Override function name from symbol table if necessary.
144 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
145 std::string FunctionName;
146 uint64_t Start, Size;
147 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
148 FunctionName, Start, Size)) {
149 LineInfo.FunctionName = FunctionName;
155 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
156 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
157 DIInliningInfo InlinedContext;
159 if (DebugInfoContext) {
160 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
161 ModuleOffset, getDILineInfoSpecifier(Opts));
163 // Make sure there is at least one frame in context.
164 if (InlinedContext.getNumberOfFrames() == 0) {
165 InlinedContext.addFrame(DILineInfo());
167 // Override the function name in lower frame with name from symbol table.
168 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
169 DIInliningInfo PatchedInlinedContext;
170 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
171 DILineInfo LineInfo = InlinedContext.getFrame(i);
173 std::string FunctionName;
174 uint64_t Start, Size;
175 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
176 FunctionName, Start, Size)) {
177 LineInfo.FunctionName = FunctionName;
180 PatchedInlinedContext.addFrame(LineInfo);
182 InlinedContext = PatchedInlinedContext;
184 return InlinedContext;
187 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
188 uint64_t &Start, uint64_t &Size) const {
189 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
193 const char LLVMSymbolizer::kBadString[] = "??";
195 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
196 uint64_t ModuleOffset) {
197 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
199 return printDILineInfo(DILineInfo());
200 if (Opts.PrintInlining) {
201 DIInliningInfo InlinedContext =
202 Info->symbolizeInlinedCode(ModuleOffset, Opts);
203 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
204 assert(FramesNum > 0);
206 for (uint32_t i = 0; i < FramesNum; i++) {
207 DILineInfo LineInfo = InlinedContext.getFrame(i);
208 Result += printDILineInfo(LineInfo);
212 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
213 return printDILineInfo(LineInfo);
216 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
217 uint64_t ModuleOffset) {
218 std::string Name = kBadString;
221 if (Opts.UseSymbolTable) {
222 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
223 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
224 Name = DemangleName(Name);
227 std::stringstream ss;
228 ss << Name << "\n" << Start << " " << Size << "\n";
232 void LLVMSymbolizer::flush() {
233 DeleteContainerSeconds(Modules);
234 ObjectPairForPathArch.clear();
235 ObjectFileForArch.clear();
238 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
239 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
240 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
241 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
243 std::string getDarwinDWARFResourceForPath(
244 const std::string &Path, const std::string &Basename) {
245 SmallString<16> ResourceName = StringRef(Path);
246 if (sys::path::extension(Path) != ".dSYM") {
247 ResourceName += ".dSYM";
249 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
250 sys::path::append(ResourceName, Basename);
251 return ResourceName.str();
254 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
255 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
256 MemoryBuffer::getFileOrSTDIN(Path);
259 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
262 static bool findDebugBinary(const std::string &OrigPath,
263 const std::string &DebuglinkName, uint32_t CRCHash,
264 std::string &Result) {
265 std::string OrigRealPath = OrigPath;
266 #if defined(HAVE_REALPATH)
267 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
272 SmallString<16> OrigDir(OrigRealPath);
273 llvm::sys::path::remove_filename(OrigDir);
274 SmallString<16> DebugPath = OrigDir;
275 // Try /path/to/original_binary/debuglink_name
276 llvm::sys::path::append(DebugPath, DebuglinkName);
277 if (checkFileCRC(DebugPath, CRCHash)) {
278 Result = DebugPath.str();
281 // Try /path/to/original_binary/.debug/debuglink_name
282 DebugPath = OrigRealPath;
283 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
284 if (checkFileCRC(DebugPath, CRCHash)) {
285 Result = DebugPath.str();
288 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
289 DebugPath = "/usr/lib/debug";
290 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
292 if (checkFileCRC(DebugPath, CRCHash)) {
293 Result = DebugPath.str();
299 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
303 for (const SectionRef &Section : Obj->sections()) {
305 Section.getName(Name);
306 Name = Name.substr(Name.find_first_not_of("._"));
307 if (Name == "gnu_debuglink") {
309 Section.getContents(Data);
310 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
312 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
313 // 4-byte align the offset.
314 Offset = (Offset + 3) & ~0x3;
315 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
316 DebugName = DebugNameStr;
317 CRCHash = DE.getU32(&Offset);
328 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
329 const MachOObjectFile *Obj) {
330 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
331 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
332 if (dbg_uuid.empty() || bin_uuid.empty())
334 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
337 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
338 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
339 // On Darwin we may find DWARF in separate object file in
340 // resource directory.
341 std::vector<std::string> DsymPaths;
342 StringRef Filename = sys::path::filename(ExePath);
343 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
344 for (const auto &Path : Opts.DsymHints) {
345 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
347 for (const auto &path : DsymPaths) {
348 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
349 std::error_code EC = BinaryOrErr.getError();
350 if (EC != errc::no_such_file_or_directory && !error(EC)) {
351 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
353 getObjectFileFromBinary(B.getBinary(), ArchName);
354 const MachOObjectFile *MachDbgObj =
355 dyn_cast<const MachOObjectFile>(DbgObj);
356 if (!MachDbgObj) continue;
357 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
358 addOwningBinary(std::move(B));
366 LLVMSymbolizer::ObjectPair
367 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
368 const std::string &ArchName) {
369 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
370 if (I != ObjectPairForPathArch.end())
372 ObjectFile *Obj = nullptr;
373 ObjectFile *DbgObj = nullptr;
374 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
375 if (!error(BinaryOrErr.getError())) {
376 OwningBinary<Binary> &B = BinaryOrErr.get();
377 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
379 ObjectPair Res = std::make_pair(nullptr, nullptr);
380 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
383 addOwningBinary(std::move(B));
384 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
385 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
386 // Try to locate the debug binary using .gnu_debuglink section.
388 std::string DebuglinkName;
390 std::string DebugBinaryPath;
391 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
392 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
393 BinaryOrErr = createBinary(DebugBinaryPath);
394 if (!error(BinaryOrErr.getError())) {
395 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
396 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
397 addOwningBinary(std::move(B));
404 ObjectPair Res = std::make_pair(Obj, DbgObj);
405 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
410 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
411 const std::string &ArchName) {
414 ObjectFile *Res = nullptr;
415 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
416 const auto &I = ObjectFileForArch.find(
417 std::make_pair(UB, ArchName));
418 if (I != ObjectFileForArch.end())
420 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
421 UB->getObjectForArch(ArchName);
423 Res = ParsedObj.get().get();
424 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
426 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
427 } else if (Bin->isObject()) {
428 Res = cast<ObjectFile>(Bin);
434 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
435 const auto &I = Modules.find(ModuleName);
436 if (I != Modules.end())
438 std::string BinaryName = ModuleName;
439 std::string ArchName = Opts.DefaultArch;
440 size_t ColonPos = ModuleName.find_last_of(':');
441 // Verify that substring after colon form a valid arch name.
442 if (ColonPos != std::string::npos) {
443 std::string ArchStr = ModuleName.substr(ColonPos + 1);
444 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
445 BinaryName = ModuleName.substr(0, ColonPos);
449 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
451 if (!Objects.first) {
452 // Failed to find valid object file.
453 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
456 DIContext *Context = nullptr;
457 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
458 // If this is a COFF object, assume it contains PDB debug information. If
459 // we don't find any we will fall back to the DWARF case.
460 std::unique_ptr<IPDBSession> Session;
461 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
462 Objects.first->getFileName(), Session);
463 if (Error == PDB_ErrorCode::Success) {
464 Context = new PDBContext(*CoffObject, std::move(Session),
465 Opts.RelativeAddresses);
469 Context = new DWARFContextInMemory(*Objects.second);
471 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
472 Modules.insert(make_pair(ModuleName, Info));
476 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
477 // By default, DILineInfo contains "<invalid>" for function/filename it
478 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
479 static const std::string kDILineInfoBadString = "<invalid>";
480 std::stringstream Result;
481 if (Opts.PrintFunctions != FunctionNameKind::None) {
482 std::string FunctionName = LineInfo.FunctionName;
483 if (FunctionName == kDILineInfoBadString)
484 FunctionName = kBadString;
485 else if (Opts.Demangle)
486 FunctionName = DemangleName(FunctionName);
487 Result << FunctionName << "\n";
489 std::string Filename = LineInfo.FileName;
490 if (Filename == kDILineInfoBadString)
491 Filename = kBadString;
492 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
496 #if !defined(_MSC_VER)
497 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
498 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
499 size_t *length, int *status);
502 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
503 #if !defined(_MSC_VER)
504 // We can spoil names of symbols with C linkage, so use an heuristic
505 // approach to check if the name should be demangled.
506 if (Name.substr(0, 2) != "_Z")
509 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
512 std::string Result = DemangledName;
516 char DemangledName[1024] = {0};
517 DWORD result = ::UnDecorateSymbolName(
518 Name.c_str(), DemangledName, 1023,
519 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
520 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
521 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
522 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
523 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
524 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
526 return (result == 0) ? Name : std::string(DemangledName);
530 } // namespace symbolize