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 std::pair<symbol_iterator, symbol_iterator> IDyn =
81 getELFDynamicSymbolIterators(Module);
82 for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
83 addSymbol(*si, OpdExtractor.get(), OpdAddress);
88 void ModuleInfo::addSymbol(const SymbolRef &Symbol, DataExtractor *OpdExtractor,
89 uint64_t OpdAddress) {
90 SymbolRef::Type SymbolType;
91 if (error(Symbol.getType(SymbolType)))
93 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
95 uint64_t SymbolAddress;
96 if (error(Symbol.getAddress(SymbolAddress)) ||
97 SymbolAddress == UnknownAddressOrSize)
100 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
101 // function descriptors. The first word of the descriptor is a pointer to
102 // the function's code.
103 // For the purposes of symbolization, pretend the symbol's address is that
104 // of the function's code, not the descriptor.
105 uint64_t OpdOffset = SymbolAddress - OpdAddress;
106 uint32_t OpdOffset32 = OpdOffset;
107 if (OpdOffset == OpdOffset32 &&
108 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
109 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
112 // Getting symbol size is linear for Mach-O files, so assume that symbol
113 // occupies the memory range up to the following symbol.
114 if (isa<MachOObjectFile>(Module))
116 else if (error(Symbol.getSize(SymbolSize)) ||
117 SymbolSize == UnknownAddressOrSize)
119 StringRef SymbolName;
120 if (error(Symbol.getName(SymbolName)))
122 // Mach-O symbol table names have leading underscore, skip it.
123 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
124 SymbolName = SymbolName.drop_front();
125 // FIXME: If a function has alias, there are two entries in symbol table
126 // with same address size. Make sure we choose the correct one.
127 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
128 SymbolDesc SD = { SymbolAddress, SymbolSize };
129 M.insert(std::make_pair(SD, SymbolName));
132 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
133 std::string &Name, uint64_t &Addr,
134 uint64_t &Size) const {
135 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
136 if (SymbolMap.empty())
138 SymbolDesc SD = { Address, Address };
139 auto SymbolIterator = SymbolMap.upper_bound(SD);
140 if (SymbolIterator == SymbolMap.begin())
143 if (SymbolIterator->first.Size != 0 &&
144 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
146 Name = SymbolIterator->second.str();
147 Addr = SymbolIterator->first.Addr;
148 Size = SymbolIterator->first.Size;
152 DILineInfo ModuleInfo::symbolizeCode(
153 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
155 if (DebugInfoContext) {
156 LineInfo = DebugInfoContext->getLineInfoForAddress(
157 ModuleOffset, getDILineInfoSpecifier(Opts));
159 // Override function name from symbol table if necessary.
160 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
161 std::string FunctionName;
162 uint64_t Start, Size;
163 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
164 FunctionName, Start, Size)) {
165 LineInfo.FunctionName = FunctionName;
171 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
172 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
173 DIInliningInfo InlinedContext;
175 if (DebugInfoContext) {
176 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
177 ModuleOffset, getDILineInfoSpecifier(Opts));
179 // Make sure there is at least one frame in context.
180 if (InlinedContext.getNumberOfFrames() == 0) {
181 InlinedContext.addFrame(DILineInfo());
183 // Override the function name in lower frame with name from symbol table.
184 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
185 DIInliningInfo PatchedInlinedContext;
186 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
187 DILineInfo LineInfo = InlinedContext.getFrame(i);
189 std::string FunctionName;
190 uint64_t Start, Size;
191 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
192 FunctionName, Start, Size)) {
193 LineInfo.FunctionName = FunctionName;
196 PatchedInlinedContext.addFrame(LineInfo);
198 InlinedContext = PatchedInlinedContext;
200 return InlinedContext;
203 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
204 uint64_t &Start, uint64_t &Size) const {
205 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
209 const char LLVMSymbolizer::kBadString[] = "??";
211 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
212 uint64_t ModuleOffset) {
213 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
215 return printDILineInfo(DILineInfo());
216 if (Opts.PrintInlining) {
217 DIInliningInfo InlinedContext =
218 Info->symbolizeInlinedCode(ModuleOffset, Opts);
219 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
220 assert(FramesNum > 0);
222 for (uint32_t i = 0; i < FramesNum; i++) {
223 DILineInfo LineInfo = InlinedContext.getFrame(i);
224 Result += printDILineInfo(LineInfo);
228 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
229 return printDILineInfo(LineInfo);
232 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
233 uint64_t ModuleOffset) {
234 std::string Name = kBadString;
237 if (Opts.UseSymbolTable) {
238 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
239 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
240 Name = DemangleName(Name);
243 std::stringstream ss;
244 ss << Name << "\n" << Start << " " << Size << "\n";
248 void LLVMSymbolizer::flush() {
249 DeleteContainerSeconds(Modules);
250 ObjectPairForPathArch.clear();
251 ObjectFileForArch.clear();
254 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
255 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
256 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
257 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
259 std::string getDarwinDWARFResourceForPath(
260 const std::string &Path, const std::string &Basename) {
261 SmallString<16> ResourceName = StringRef(Path);
262 if (sys::path::extension(Path) != ".dSYM") {
263 ResourceName += ".dSYM";
265 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
266 sys::path::append(ResourceName, Basename);
267 return ResourceName.str();
270 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
271 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
272 MemoryBuffer::getFileOrSTDIN(Path);
275 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
278 static bool findDebugBinary(const std::string &OrigPath,
279 const std::string &DebuglinkName, uint32_t CRCHash,
280 std::string &Result) {
281 std::string OrigRealPath = OrigPath;
282 #if defined(HAVE_REALPATH)
283 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
288 SmallString<16> OrigDir(OrigRealPath);
289 llvm::sys::path::remove_filename(OrigDir);
290 SmallString<16> DebugPath = OrigDir;
291 // Try /path/to/original_binary/debuglink_name
292 llvm::sys::path::append(DebugPath, DebuglinkName);
293 if (checkFileCRC(DebugPath, CRCHash)) {
294 Result = DebugPath.str();
297 // Try /path/to/original_binary/.debug/debuglink_name
298 DebugPath = OrigRealPath;
299 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
300 if (checkFileCRC(DebugPath, CRCHash)) {
301 Result = DebugPath.str();
304 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
305 DebugPath = "/usr/lib/debug";
306 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
308 if (checkFileCRC(DebugPath, CRCHash)) {
309 Result = DebugPath.str();
315 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
319 for (const SectionRef &Section : Obj->sections()) {
321 Section.getName(Name);
322 Name = Name.substr(Name.find_first_not_of("._"));
323 if (Name == "gnu_debuglink") {
325 Section.getContents(Data);
326 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
328 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
329 // 4-byte align the offset.
330 Offset = (Offset + 3) & ~0x3;
331 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
332 DebugName = DebugNameStr;
333 CRCHash = DE.getU32(&Offset);
344 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
345 const MachOObjectFile *Obj) {
346 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
347 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
348 if (dbg_uuid.empty() || bin_uuid.empty())
350 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
353 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
354 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
355 // On Darwin we may find DWARF in separate object file in
356 // resource directory.
357 std::vector<std::string> DsymPaths;
358 StringRef Filename = sys::path::filename(ExePath);
359 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
360 for (const auto &Path : Opts.DsymHints) {
361 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
363 for (const auto &path : DsymPaths) {
364 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
365 std::error_code EC = BinaryOrErr.getError();
366 if (EC != errc::no_such_file_or_directory && !error(EC)) {
367 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
369 getObjectFileFromBinary(B.getBinary(), ArchName);
370 const MachOObjectFile *MachDbgObj =
371 dyn_cast<const MachOObjectFile>(DbgObj);
372 if (!MachDbgObj) continue;
373 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
374 addOwningBinary(std::move(B));
382 LLVMSymbolizer::ObjectPair
383 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
384 const std::string &ArchName) {
385 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
386 if (I != ObjectPairForPathArch.end())
388 ObjectFile *Obj = nullptr;
389 ObjectFile *DbgObj = nullptr;
390 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
391 if (!error(BinaryOrErr.getError())) {
392 OwningBinary<Binary> &B = BinaryOrErr.get();
393 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
395 ObjectPair Res = std::make_pair(nullptr, nullptr);
396 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
399 addOwningBinary(std::move(B));
400 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
401 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
402 // Try to locate the debug binary using .gnu_debuglink section.
404 std::string DebuglinkName;
406 std::string DebugBinaryPath;
407 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
408 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
409 BinaryOrErr = createBinary(DebugBinaryPath);
410 if (!error(BinaryOrErr.getError())) {
411 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
412 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
413 addOwningBinary(std::move(B));
420 ObjectPair Res = std::make_pair(Obj, DbgObj);
421 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
426 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
427 const std::string &ArchName) {
430 ObjectFile *Res = nullptr;
431 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
432 const auto &I = ObjectFileForArch.find(
433 std::make_pair(UB, ArchName));
434 if (I != ObjectFileForArch.end())
436 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
437 UB->getObjectForArch(Triple(ArchName).getArch());
439 Res = ParsedObj.get().get();
440 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
442 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
443 } else if (Bin->isObject()) {
444 Res = cast<ObjectFile>(Bin);
450 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
451 const auto &I = Modules.find(ModuleName);
452 if (I != Modules.end())
454 std::string BinaryName = ModuleName;
455 std::string ArchName = Opts.DefaultArch;
456 size_t ColonPos = ModuleName.find_last_of(':');
457 // Verify that substring after colon form a valid arch name.
458 if (ColonPos != std::string::npos) {
459 std::string ArchStr = ModuleName.substr(ColonPos + 1);
460 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
461 BinaryName = ModuleName.substr(0, ColonPos);
465 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
467 if (!Objects.first) {
468 // Failed to find valid object file.
469 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
472 DIContext *Context = nullptr;
473 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
474 // If this is a COFF object, assume it contains PDB debug information. If
475 // we don't find any we will fall back to the DWARF case.
476 std::unique_ptr<IPDBSession> Session;
477 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
478 Objects.first->getFileName(), Session);
479 if (Error == PDB_ErrorCode::Success) {
480 Context = new PDBContext(*CoffObject, std::move(Session),
481 Opts.RelativeAddresses);
485 Context = new DWARFContextInMemory(*Objects.second);
487 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
488 Modules.insert(make_pair(ModuleName, Info));
492 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
493 // By default, DILineInfo contains "<invalid>" for function/filename it
494 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
495 static const std::string kDILineInfoBadString = "<invalid>";
496 std::stringstream Result;
497 if (Opts.PrintFunctions != FunctionNameKind::None) {
498 std::string FunctionName = LineInfo.FunctionName;
499 if (FunctionName == kDILineInfoBadString)
500 FunctionName = kBadString;
501 else if (Opts.Demangle)
502 FunctionName = DemangleName(FunctionName);
503 Result << FunctionName << "\n";
505 std::string Filename = LineInfo.FileName;
506 if (Filename == kDILineInfoBadString)
507 Filename = kBadString;
508 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
512 #if !defined(_MSC_VER)
513 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
514 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
515 size_t *length, int *status);
518 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
519 #if !defined(_MSC_VER)
520 // We can spoil names of symbols with C linkage, so use an heuristic
521 // approach to check if the name should be demangled.
522 if (Name.substr(0, 2) != "_Z")
525 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
528 std::string Result = DemangledName;
532 char DemangledName[1024] = {0};
533 DWORD result = ::UnDecorateSymbolName(
534 Name.c_str(), DemangledName, 1023,
535 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
536 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
537 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
538 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
539 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
540 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
542 return (result == 0) ? Name : std::string(DemangledName);
546 } // namespace symbolize