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 ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName();
104 if (error(SymbolNameOrErr.getError()))
106 StringRef SymbolName = *SymbolNameOrErr;
107 // Mach-O symbol table names have leading underscore, skip it.
108 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
109 SymbolName = SymbolName.drop_front();
110 // FIXME: If a function has alias, there are two entries in symbol table
111 // with same address size. Make sure we choose the correct one.
112 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
113 SymbolDesc SD = { SymbolAddress, SymbolSize };
114 M.insert(std::make_pair(SD, SymbolName));
117 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
118 std::string &Name, uint64_t &Addr,
119 uint64_t &Size) const {
120 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
121 if (SymbolMap.empty())
123 SymbolDesc SD = { Address, Address };
124 auto SymbolIterator = SymbolMap.upper_bound(SD);
125 if (SymbolIterator == SymbolMap.begin())
128 if (SymbolIterator->first.Size != 0 &&
129 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
131 Name = SymbolIterator->second.str();
132 Addr = SymbolIterator->first.Addr;
133 Size = SymbolIterator->first.Size;
137 DILineInfo ModuleInfo::symbolizeCode(
138 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
140 if (DebugInfoContext) {
141 LineInfo = DebugInfoContext->getLineInfoForAddress(
142 ModuleOffset, getDILineInfoSpecifier(Opts));
144 // Override function name from symbol table if necessary.
145 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
146 std::string FunctionName;
147 uint64_t Start, Size;
148 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
149 FunctionName, Start, Size)) {
150 LineInfo.FunctionName = FunctionName;
156 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
157 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
158 DIInliningInfo InlinedContext;
160 if (DebugInfoContext) {
161 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
162 ModuleOffset, getDILineInfoSpecifier(Opts));
164 // Make sure there is at least one frame in context.
165 if (InlinedContext.getNumberOfFrames() == 0) {
166 InlinedContext.addFrame(DILineInfo());
168 // Override the function name in lower frame with name from symbol table.
169 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
170 DIInliningInfo PatchedInlinedContext;
171 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
172 DILineInfo LineInfo = InlinedContext.getFrame(i);
174 std::string FunctionName;
175 uint64_t Start, Size;
176 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
177 FunctionName, Start, Size)) {
178 LineInfo.FunctionName = FunctionName;
181 PatchedInlinedContext.addFrame(LineInfo);
183 InlinedContext = PatchedInlinedContext;
185 return InlinedContext;
188 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
189 uint64_t &Start, uint64_t &Size) const {
190 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
194 const char LLVMSymbolizer::kBadString[] = "??";
196 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
197 uint64_t ModuleOffset) {
198 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
200 return printDILineInfo(DILineInfo());
201 if (Opts.PrintInlining) {
202 DIInliningInfo InlinedContext =
203 Info->symbolizeInlinedCode(ModuleOffset, Opts);
204 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
205 assert(FramesNum > 0);
207 for (uint32_t i = 0; i < FramesNum; i++) {
208 DILineInfo LineInfo = InlinedContext.getFrame(i);
209 Result += printDILineInfo(LineInfo);
213 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
214 return printDILineInfo(LineInfo);
217 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
218 uint64_t ModuleOffset) {
219 std::string Name = kBadString;
222 if (Opts.UseSymbolTable) {
223 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
224 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
225 Name = DemangleName(Name);
228 std::stringstream ss;
229 ss << Name << "\n" << Start << " " << Size << "\n";
233 void LLVMSymbolizer::flush() {
234 DeleteContainerSeconds(Modules);
235 ObjectPairForPathArch.clear();
236 ObjectFileForArch.clear();
239 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
240 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
241 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
242 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
244 std::string getDarwinDWARFResourceForPath(
245 const std::string &Path, const std::string &Basename) {
246 SmallString<16> ResourceName = StringRef(Path);
247 if (sys::path::extension(Path) != ".dSYM") {
248 ResourceName += ".dSYM";
250 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
251 sys::path::append(ResourceName, Basename);
252 return ResourceName.str();
255 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
256 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
257 MemoryBuffer::getFileOrSTDIN(Path);
260 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
263 static bool findDebugBinary(const std::string &OrigPath,
264 const std::string &DebuglinkName, uint32_t CRCHash,
265 std::string &Result) {
266 std::string OrigRealPath = OrigPath;
267 #if defined(HAVE_REALPATH)
268 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
273 SmallString<16> OrigDir(OrigRealPath);
274 llvm::sys::path::remove_filename(OrigDir);
275 SmallString<16> DebugPath = OrigDir;
276 // Try /path/to/original_binary/debuglink_name
277 llvm::sys::path::append(DebugPath, DebuglinkName);
278 if (checkFileCRC(DebugPath, CRCHash)) {
279 Result = DebugPath.str();
282 // Try /path/to/original_binary/.debug/debuglink_name
283 DebugPath = OrigRealPath;
284 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
285 if (checkFileCRC(DebugPath, CRCHash)) {
286 Result = DebugPath.str();
289 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
290 DebugPath = "/usr/lib/debug";
291 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
293 if (checkFileCRC(DebugPath, CRCHash)) {
294 Result = DebugPath.str();
300 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
304 for (const SectionRef &Section : Obj->sections()) {
306 Section.getName(Name);
307 Name = Name.substr(Name.find_first_not_of("._"));
308 if (Name == "gnu_debuglink") {
310 Section.getContents(Data);
311 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
313 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
314 // 4-byte align the offset.
315 Offset = (Offset + 3) & ~0x3;
316 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
317 DebugName = DebugNameStr;
318 CRCHash = DE.getU32(&Offset);
329 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
330 const MachOObjectFile *Obj) {
331 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
332 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
333 if (dbg_uuid.empty() || bin_uuid.empty())
335 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
338 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
339 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
340 // On Darwin we may find DWARF in separate object file in
341 // resource directory.
342 std::vector<std::string> DsymPaths;
343 StringRef Filename = sys::path::filename(ExePath);
344 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
345 for (const auto &Path : Opts.DsymHints) {
346 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
348 for (const auto &path : DsymPaths) {
349 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
350 std::error_code EC = BinaryOrErr.getError();
351 if (EC != errc::no_such_file_or_directory && !error(EC)) {
352 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
354 getObjectFileFromBinary(B.getBinary(), ArchName);
355 const MachOObjectFile *MachDbgObj =
356 dyn_cast<const MachOObjectFile>(DbgObj);
357 if (!MachDbgObj) continue;
358 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
359 addOwningBinary(std::move(B));
367 LLVMSymbolizer::ObjectPair
368 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
369 const std::string &ArchName) {
370 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
371 if (I != ObjectPairForPathArch.end())
373 ObjectFile *Obj = nullptr;
374 ObjectFile *DbgObj = nullptr;
375 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
376 if (!error(BinaryOrErr.getError())) {
377 OwningBinary<Binary> &B = BinaryOrErr.get();
378 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
380 ObjectPair Res = std::make_pair(nullptr, nullptr);
381 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
384 addOwningBinary(std::move(B));
385 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
386 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
387 // Try to locate the debug binary using .gnu_debuglink section.
389 std::string DebuglinkName;
391 std::string DebugBinaryPath;
392 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
393 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
394 BinaryOrErr = createBinary(DebugBinaryPath);
395 if (!error(BinaryOrErr.getError())) {
396 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
397 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
398 addOwningBinary(std::move(B));
405 ObjectPair Res = std::make_pair(Obj, DbgObj);
406 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
411 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
412 const std::string &ArchName) {
415 ObjectFile *Res = nullptr;
416 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
417 const auto &I = ObjectFileForArch.find(
418 std::make_pair(UB, ArchName));
419 if (I != ObjectFileForArch.end())
421 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
422 UB->getObjectForArch(ArchName);
424 Res = ParsedObj.get().get();
425 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
427 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
428 } else if (Bin->isObject()) {
429 Res = cast<ObjectFile>(Bin);
435 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
436 const auto &I = Modules.find(ModuleName);
437 if (I != Modules.end())
439 std::string BinaryName = ModuleName;
440 std::string ArchName = Opts.DefaultArch;
441 size_t ColonPos = ModuleName.find_last_of(':');
442 // Verify that substring after colon form a valid arch name.
443 if (ColonPos != std::string::npos) {
444 std::string ArchStr = ModuleName.substr(ColonPos + 1);
445 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
446 BinaryName = ModuleName.substr(0, ColonPos);
450 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
452 if (!Objects.first) {
453 // Failed to find valid object file.
454 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
457 DIContext *Context = nullptr;
458 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
459 // If this is a COFF object, assume it contains PDB debug information. If
460 // we don't find any we will fall back to the DWARF case.
461 std::unique_ptr<IPDBSession> Session;
462 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
463 Objects.first->getFileName(), Session);
464 if (Error == PDB_ErrorCode::Success) {
465 Context = new PDBContext(*CoffObject, std::move(Session),
466 Opts.RelativeAddresses);
470 Context = new DWARFContextInMemory(*Objects.second);
472 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
473 Modules.insert(make_pair(ModuleName, Info));
477 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
478 // By default, DILineInfo contains "<invalid>" for function/filename it
479 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
480 static const std::string kDILineInfoBadString = "<invalid>";
481 std::stringstream Result;
482 if (Opts.PrintFunctions != FunctionNameKind::None) {
483 std::string FunctionName = LineInfo.FunctionName;
484 if (FunctionName == kDILineInfoBadString)
485 FunctionName = kBadString;
486 else if (Opts.Demangle)
487 FunctionName = DemangleName(FunctionName);
488 Result << FunctionName << "\n";
490 std::string Filename = LineInfo.FileName;
491 if (Filename == kDILineInfoBadString)
492 Filename = kBadString;
493 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
497 #if !defined(_MSC_VER)
498 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
499 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
500 size_t *length, int *status);
503 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
504 #if !defined(_MSC_VER)
505 // We can spoil names of symbols with C linkage, so use an heuristic
506 // approach to check if the name should be demangled.
507 if (Name.substr(0, 2) != "_Z")
510 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
513 std::string Result = DemangledName;
517 char DemangledName[1024] = {0};
518 DWORD result = ::UnDecorateSymbolName(
519 Name.c_str(), DemangledName, 1023,
520 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
521 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
522 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
523 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
524 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
525 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
527 return (result == 0) ? Name : std::string(DemangledName);
531 } // namespace symbolize