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 == UnknownAddress)
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 // Onyl ELF has a size for every symbol so assume that symbol occupies the
113 // memory range up to the following symbol.
114 if (auto *E = dyn_cast<ELFObjectFileBase>(Module))
115 SymbolSize = E->getSymbolSize(Symbol);
118 StringRef SymbolName;
119 if (error(Symbol.getName(SymbolName)))
121 // Mach-O symbol table names have leading underscore, skip it.
122 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
123 SymbolName = SymbolName.drop_front();
124 // FIXME: If a function has alias, there are two entries in symbol table
125 // with same address size. Make sure we choose the correct one.
126 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
127 SymbolDesc SD = { SymbolAddress, SymbolSize };
128 M.insert(std::make_pair(SD, SymbolName));
131 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
132 std::string &Name, uint64_t &Addr,
133 uint64_t &Size) const {
134 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
135 if (SymbolMap.empty())
137 SymbolDesc SD = { Address, Address };
138 auto SymbolIterator = SymbolMap.upper_bound(SD);
139 if (SymbolIterator == SymbolMap.begin())
142 if (SymbolIterator->first.Size != 0 &&
143 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
145 Name = SymbolIterator->second.str();
146 Addr = SymbolIterator->first.Addr;
147 Size = SymbolIterator->first.Size;
151 DILineInfo ModuleInfo::symbolizeCode(
152 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
154 if (DebugInfoContext) {
155 LineInfo = DebugInfoContext->getLineInfoForAddress(
156 ModuleOffset, getDILineInfoSpecifier(Opts));
158 // Override function name from symbol table if necessary.
159 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
160 std::string FunctionName;
161 uint64_t Start, Size;
162 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
163 FunctionName, Start, Size)) {
164 LineInfo.FunctionName = FunctionName;
170 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
171 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
172 DIInliningInfo InlinedContext;
174 if (DebugInfoContext) {
175 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
176 ModuleOffset, getDILineInfoSpecifier(Opts));
178 // Make sure there is at least one frame in context.
179 if (InlinedContext.getNumberOfFrames() == 0) {
180 InlinedContext.addFrame(DILineInfo());
182 // Override the function name in lower frame with name from symbol table.
183 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
184 DIInliningInfo PatchedInlinedContext;
185 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
186 DILineInfo LineInfo = InlinedContext.getFrame(i);
188 std::string FunctionName;
189 uint64_t Start, Size;
190 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
191 FunctionName, Start, Size)) {
192 LineInfo.FunctionName = FunctionName;
195 PatchedInlinedContext.addFrame(LineInfo);
197 InlinedContext = PatchedInlinedContext;
199 return InlinedContext;
202 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
203 uint64_t &Start, uint64_t &Size) const {
204 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
208 const char LLVMSymbolizer::kBadString[] = "??";
210 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
211 uint64_t ModuleOffset) {
212 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
214 return printDILineInfo(DILineInfo());
215 if (Opts.PrintInlining) {
216 DIInliningInfo InlinedContext =
217 Info->symbolizeInlinedCode(ModuleOffset, Opts);
218 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
219 assert(FramesNum > 0);
221 for (uint32_t i = 0; i < FramesNum; i++) {
222 DILineInfo LineInfo = InlinedContext.getFrame(i);
223 Result += printDILineInfo(LineInfo);
227 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
228 return printDILineInfo(LineInfo);
231 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
232 uint64_t ModuleOffset) {
233 std::string Name = kBadString;
236 if (Opts.UseSymbolTable) {
237 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
238 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
239 Name = DemangleName(Name);
242 std::stringstream ss;
243 ss << Name << "\n" << Start << " " << Size << "\n";
247 void LLVMSymbolizer::flush() {
248 DeleteContainerSeconds(Modules);
249 ObjectPairForPathArch.clear();
250 ObjectFileForArch.clear();
253 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
254 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
255 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
256 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
258 std::string getDarwinDWARFResourceForPath(
259 const std::string &Path, const std::string &Basename) {
260 SmallString<16> ResourceName = StringRef(Path);
261 if (sys::path::extension(Path) != ".dSYM") {
262 ResourceName += ".dSYM";
264 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
265 sys::path::append(ResourceName, Basename);
266 return ResourceName.str();
269 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
270 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
271 MemoryBuffer::getFileOrSTDIN(Path);
274 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
277 static bool findDebugBinary(const std::string &OrigPath,
278 const std::string &DebuglinkName, uint32_t CRCHash,
279 std::string &Result) {
280 std::string OrigRealPath = OrigPath;
281 #if defined(HAVE_REALPATH)
282 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
287 SmallString<16> OrigDir(OrigRealPath);
288 llvm::sys::path::remove_filename(OrigDir);
289 SmallString<16> DebugPath = OrigDir;
290 // Try /path/to/original_binary/debuglink_name
291 llvm::sys::path::append(DebugPath, DebuglinkName);
292 if (checkFileCRC(DebugPath, CRCHash)) {
293 Result = DebugPath.str();
296 // Try /path/to/original_binary/.debug/debuglink_name
297 DebugPath = OrigRealPath;
298 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
299 if (checkFileCRC(DebugPath, CRCHash)) {
300 Result = DebugPath.str();
303 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
304 DebugPath = "/usr/lib/debug";
305 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
307 if (checkFileCRC(DebugPath, CRCHash)) {
308 Result = DebugPath.str();
314 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
318 for (const SectionRef &Section : Obj->sections()) {
320 Section.getName(Name);
321 Name = Name.substr(Name.find_first_not_of("._"));
322 if (Name == "gnu_debuglink") {
324 Section.getContents(Data);
325 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
327 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
328 // 4-byte align the offset.
329 Offset = (Offset + 3) & ~0x3;
330 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
331 DebugName = DebugNameStr;
332 CRCHash = DE.getU32(&Offset);
343 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
344 const MachOObjectFile *Obj) {
345 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
346 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
347 if (dbg_uuid.empty() || bin_uuid.empty())
349 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
352 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
353 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
354 // On Darwin we may find DWARF in separate object file in
355 // resource directory.
356 std::vector<std::string> DsymPaths;
357 StringRef Filename = sys::path::filename(ExePath);
358 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
359 for (const auto &Path : Opts.DsymHints) {
360 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
362 for (const auto &path : DsymPaths) {
363 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
364 std::error_code EC = BinaryOrErr.getError();
365 if (EC != errc::no_such_file_or_directory && !error(EC)) {
366 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
368 getObjectFileFromBinary(B.getBinary(), ArchName);
369 const MachOObjectFile *MachDbgObj =
370 dyn_cast<const MachOObjectFile>(DbgObj);
371 if (!MachDbgObj) continue;
372 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
373 addOwningBinary(std::move(B));
381 LLVMSymbolizer::ObjectPair
382 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
383 const std::string &ArchName) {
384 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
385 if (I != ObjectPairForPathArch.end())
387 ObjectFile *Obj = nullptr;
388 ObjectFile *DbgObj = nullptr;
389 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
390 if (!error(BinaryOrErr.getError())) {
391 OwningBinary<Binary> &B = BinaryOrErr.get();
392 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
394 ObjectPair Res = std::make_pair(nullptr, nullptr);
395 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
398 addOwningBinary(std::move(B));
399 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
400 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
401 // Try to locate the debug binary using .gnu_debuglink section.
403 std::string DebuglinkName;
405 std::string DebugBinaryPath;
406 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
407 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
408 BinaryOrErr = createBinary(DebugBinaryPath);
409 if (!error(BinaryOrErr.getError())) {
410 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
411 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
412 addOwningBinary(std::move(B));
419 ObjectPair Res = std::make_pair(Obj, DbgObj);
420 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
425 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
426 const std::string &ArchName) {
429 ObjectFile *Res = nullptr;
430 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
431 const auto &I = ObjectFileForArch.find(
432 std::make_pair(UB, ArchName));
433 if (I != ObjectFileForArch.end())
435 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
436 UB->getObjectForArch(ArchName);
438 Res = ParsedObj.get().get();
439 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
441 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
442 } else if (Bin->isObject()) {
443 Res = cast<ObjectFile>(Bin);
449 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
450 const auto &I = Modules.find(ModuleName);
451 if (I != Modules.end())
453 std::string BinaryName = ModuleName;
454 std::string ArchName = Opts.DefaultArch;
455 size_t ColonPos = ModuleName.find_last_of(':');
456 // Verify that substring after colon form a valid arch name.
457 if (ColonPos != std::string::npos) {
458 std::string ArchStr = ModuleName.substr(ColonPos + 1);
459 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
460 BinaryName = ModuleName.substr(0, ColonPos);
464 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
466 if (!Objects.first) {
467 // Failed to find valid object file.
468 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
471 DIContext *Context = nullptr;
472 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
473 // If this is a COFF object, assume it contains PDB debug information. If
474 // we don't find any we will fall back to the DWARF case.
475 std::unique_ptr<IPDBSession> Session;
476 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
477 Objects.first->getFileName(), Session);
478 if (Error == PDB_ErrorCode::Success) {
479 Context = new PDBContext(*CoffObject, std::move(Session),
480 Opts.RelativeAddresses);
484 Context = new DWARFContextInMemory(*Objects.second);
486 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
487 Modules.insert(make_pair(ModuleName, Info));
491 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
492 // By default, DILineInfo contains "<invalid>" for function/filename it
493 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
494 static const std::string kDILineInfoBadString = "<invalid>";
495 std::stringstream Result;
496 if (Opts.PrintFunctions != FunctionNameKind::None) {
497 std::string FunctionName = LineInfo.FunctionName;
498 if (FunctionName == kDILineInfoBadString)
499 FunctionName = kBadString;
500 else if (Opts.Demangle)
501 FunctionName = DemangleName(FunctionName);
502 Result << FunctionName << "\n";
504 std::string Filename = LineInfo.FileName;
505 if (Filename == kDILineInfoBadString)
506 Filename = kBadString;
507 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
511 #if !defined(_MSC_VER)
512 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
513 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
514 size_t *length, int *status);
517 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
518 #if !defined(_MSC_VER)
519 // We can spoil names of symbols with C linkage, so use an heuristic
520 // approach to check if the name should be demangled.
521 if (Name.substr(0, 2) != "_Z")
524 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
527 std::string Result = DemangledName;
531 char DemangledName[1024] = {0};
532 DWORD result = ::UnDecorateSymbolName(
533 Name.c_str(), DemangledName, 1023,
534 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
535 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
536 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
537 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
538 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
539 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
541 return (result == 0) ? Name : std::string(DemangledName);
545 } // namespace symbolize